【问题标题】:Set ordering of Apps and models in Django admin dashboard在 Django 管理仪表板中设置应用程序和模型的顺序
【发布时间】:2019-10-06 09:59:18
【问题描述】:

默认情况下,Django 管理仪表板对我来说是这样的:

我想更改 Profile 部分中模型的顺序,因此通过使用 herehere 中的代码,我能够在 Django 管理仪表板中更改模型名称的顺序:

class MyAdminSite(admin.AdminSite):
    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        ordering = {
            "Users": 1,
            "Permissions": 2,
            "Activities": 3,
        }
        app_dict = self._build_app_dict(request)
        # a.sort(key=lambda x: b.index(x[0]))
        # 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: ordering[x['name']])

        return app_list

mysite = MyAdminSite()
admin.site = mysite
sites.site = mysite

新的外观和感觉:

但是如你所见,我丢失了AUTHENTICATION AND AUTHORIZATION 部分;我应该怎么做才能拥有所有部分,同时对Profile 部分有自己的自定义排序?

【问题讨论】:

    标签: django


    【解决方案1】:

    首先用super 致电get_app_list(),就像这样:

    class MyAdminSite(admin.AdminSite):
    def get_app_list(self, request):
        all_list = super().get_app_list(request)
        # reorder the app list as you like
        return app_list
    
    
    mysite = MyAdminSite()
    admin.site = mysite
    sites.site = mysite
    

    【讨论】:

    • all_list = super().get_app_list(request) 仍然只返回配置文件部分,而不是所有应用程序和模型。
    【解决方案2】:

    你可以做的就是重写get_app_list方法。

    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
    
    admin.AdminSite.get_app_list = get_app_list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2014-05-04
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多