关于django:Custom-models-display-ordering-for-Django-admin-dashboard

56次阅读

共计 1668 个字符,预计需要花费 5 分钟才能阅读完成。

Django Admin

By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order.

https://docs.djangoproject.com/en/3.1/intro/tutorial07/#customize-the-admin-index-page

    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        app_dict = self._build_app_dict(request)

        # Sort the apps alphabetically.
        app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

        return app_list

https://github.com/django/django/blob/8bca838f4a230b78dd44fc1db3c1b81e444c6099/django/contrib/admin/sites.py#L501

There are multiple ways to achieve this on the internet

  • Adding a numeric prefix for each verbose_name_plural in App Model Meta
  • Override admin/base.html tempalte
  • Override AdminSite class and get_app_list() method

For this article, I will be using a way that to override the get_app_list class method only without overriding the class.

How to do it?

Define the class method normally.

def get_app_list(self, request):
    """
    Return a sorted list of all the installed apps that have been
    registered in this site.
    """
    # Retrieve the original list
    app_dict = self._build_app_dict(request)
    app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())

    # Sort the models customably within each app.
    for app in app_list:
        if app['app_label'] == 'auth':
            ordering = {
                'Users': 1,
                'Groups': 2
            }
            app['models'].sort(key=lambda x: ordering[x['name']])

    return app_list

Some things to take note,

  1. Retrieve the original list
  2. Define the ordering for each app, as the model names are different
  3. I am using app_lable to specify which app to apply
  4. The medel name is verbose_name_plural or verbose_name

Then update the method with custom method

admin.AdminSite.get_app_list = get_app_list

正文完
 0