微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django管理员 – 如何获取模板中的所有注册模型?

我正在编写一个自定义管理员资料,需要在管理员中获得所有注册的模型.这可能吗?我需要它在管理员索引页面上进行一些自定义视图.

解决方法

您可以访问Model-> ModelAdmin的admin.site._registry dict:
>>> ./manage.py shell

In [1]: from urls import * # load admin

In [2]: from django.contrib import admin

In [3]: admin.site._registry
Out[3]: 
{django.contrib.auth.models.Group: <django.contrib.auth.admin.GroupAdmin at 0x22629d0>,django.contrib.auth.models.User: <django.contrib.auth.admin.UserAdmin at 0x2262a10>,django.contrib.sites.models.Site: <django.contrib.sites.admin.SiteAdmin at 0x2262c90>,testapp.models.Up: <django.contrib.admin.options.ModelAdmin at 0x2269c10>,nashvegas.models.Migration: <nashvegas.admin.MigrationAdmin at 0x2262ad0>}

这是管理员索引视图的作用:

@never_cache
def index(self,request,extra_context=None):
    """ 
    displays the main admin index page,which lists all of the installed
    apps that have been registered in this site.
    """
    app_dict = {}
    user = request.user
    for model,model_admin in self._registry.items():
        # ...

请注意,以下划线为前缀的变量可能会在将来的django版本中发生更改.

原文地址:https://www.jb51.cc/python/185658.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐