在 django 管理索引页面中定义自定义 app_list [英] Defining a custom app_list in django admin index page

查看:20
本文介绍了在 django 管理索引页面中定义自定义 app_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个自定义应用程序列表以在 django 的管理索引页面中使用,因为我希望应用程序以特定顺序显示,而不是默认的字母顺序.浏览各种 SO 帖子,似乎还不能在任何明显的地方(例如 admin.py、models.py)声明所需的应用程序顺序.

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 alphabetical order. Trawling through various SO posts it would appear that it's not yet possible to declare the desired application order in any of the obvious places (e.g. admin.py, models.py).

现在,我可以看到 django admin 的 index.html 文件包含以下语句:

Now, I can see that the django admin's index.html file contains the following statement:

{% for app in app_list %}
   # do stuff with the app object

所以我想将其更改为使用名为 my_app_list 的自定义列表对象.在 python 中,我会按照以下方式执行此操作:

So I'd like to change this to use a custom list object called, say, my_app_list. In python I'd do this along the following lines:

from django.db.models import get_app
my_app_list = [get_app('myapp1'), get_app('myapp2'), ..., get_app('django.contrib.auth')]
for app in my_app_list
   ...

那么我的问题是,我如何将上面前 2 行的等效代码编码到我的 index.html 文件的本地副本中?

My question then is, how do I code the equivalent of the first 2 lines above into my local copy of the index.html file?

或者,或者,我应该将这些行插入到哪个 python 源文件中,以便变量 my_app_list 在 index.html 中可用.

Or, alternatively, what python source file should I insert those lines into such that the variable my_app_list is available within index.html.

提前致谢.

菲尔

推荐答案

子类django.contrib.admin.site.AdminSite().覆盖 .index() 方法,并执行以下操作:

Subclass django.contrib.admin.site.AdminSite(). Override the .index() method, and do something like this:

class MyAdminSite(django.contrib.admin.site.AdminSite):
    def index(self, request, extra_context=None):
        if extra_context is None:
            extra_context = {}
        extra_context["app_list"] = get_app_list_in_custom_order()
        return super(MyAdminSite, self).index(request, extra_context)

使用 my_admin_site = MyAdminSite() 实例化此子类的实例,将模型附加到它(使用通常的 my_admin_site.register()),并将其附加到网址配置;应该这样做.

Instantiate an instance of this subclass with my_admin_site = MyAdminSite(), attach your models to it (using the usual my_admin_site.register()), and attach it to the URLconf; that should do it.

(我没有尝试过这个,我是根据我对 AdminSite 源代码的阅读.)

(I haven't tried this, I'm basing this on my reading of the AdminSite source.)

这篇关于在 django 管理索引页面中定义自定义 app_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆