python - 为什么需要在 Django admin 中同时注册应用程序名称和应用程序管理员名称?

标签 python django django-admin

我试图理解为什么在为 django 应用程序添加自定义管理站点时,需要同时添加模型和管理功能。假设您有一个名为 Story 的应用程序,因此管理站点将称为 StoryAdmin。在 django 管理界面注册时,需要添加以下行:

# Registering all the changes to admin.site
admin.site.register(Story, StoryAdmin)

我的问题是,有没有办法做到这一点:

admin.site.register(StoryAdmin)

只添加一件事,而不是两件事,因为这会让事情变得更简单,并且出错的机会更小,而且代码看起来不那么冗余。这会让事情看起来好多了,因为最后,您可以得到所有管理面板的干净列表:

admin.site.register(
    StoryAdmin,
    SomeAdmin,
    FooAdmin,
)

最佳答案

That's not how admin.site.register is built 。它需要一个模型,然后可以选择使用 ModelAdmin 来显示该模型:

def register(self, model_or_iterable, admin_class=None, **options):
    """
    Registers the given model(s) with the given admin class.

    The model(s) should be Model classes, not instances.

    If an admin class isn't given, it will use ModelAdmin (the default
    admin options). If keyword arguments are given -- e.g., list_display --
    they'll be applied as options to the admin class.

    If a model is already registered, this will raise AlreadyRegistered.

    If a model is abstract, this will raise ImproperlyConfigured.
    """

这允许您在多个模型上使用相同的 ModelAdmin(例如,当您从同一抽象模型子类化模型时,这可能是理想的)。

它不适合您的风格,但它只是您必须接受并继续下去的事情之一。

关于python - 为什么需要在 Django admin 中同时注册应用程序名称和应用程序管理员名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854516/

相关文章:

Django 1.7升级报错: AppRegistryNotReady: Apps aren't loaded yet

python - 在 django admin 中过滤下拉值

python - 随机替换字符串的某些部分

Python 基础 : How to convert a list containing an int into a plain int?

python - Django中抽象模型类与多表继承的结合

python - 如何防止 AWS EC2 服务器无限期运行?

Python3,在pandas数据框中添加不同数量的列

python - 基于另一列中的部分字符串匹配的列的条件更新

python - 对 admin.py 的更新未反射(reflect)在 django 管理页面中

Django admin,隐藏一个模型