Defining a custom app_list in django admin index page

前端 未结 5 574
面向向阳花
面向向阳花 2020-12-28 08:36

I\'d like to define a custom application list to use in django\'s admin index page because I want the apps displayed in a specific order, rather than the default alphabetica

5条回答
  •  长发绾君心
    2020-12-28 08:49

    Since you are concerned about the order, you can find my solution helpful.
    Basically, I created a filter, which moves desired elements of app_list to the beginning.

    @register.filter
    def put_it_first(value, arg):
        '''The filter shifts specified items in app_list to the top,
        the syntax is: LIST_TO_PROCESS|put_it_first:"1st_item[;2nd_item...]"
        '''
        def _cust_sort(x):
            try:
                return arg.index(x['name'].lower())
            except ValueError:
                return dist
        arg = arg.split(';')
        arg = map(unicode.lower, arg)
        dist = len(arg) + 1
        value.sort(key=_cust_sort)
        return value
    

    However, if you need to remove some elements you can use:

    @register.filter
    def remove_some(value, arg):
        '''The filter removes specified items from app_list,
        the syntax is: LIST_TO_PROCESS|remove_some:"1st_item[;2nd_item...]"
        '''
        arg = arg.split(';')
        arg = map(unicode.lower, arg)
        return [v for v in value if v['name'].lower() not in arg]
    

    Filters can be chained, so you can use both at the same time.
    Filtering functions are not written the way which would make them speed demons, but this template is not being rendered too often by definition.

提交回复
热议问题