【问题标题】:Running a system check after AppRegistry is initialized - Django Admin初始化 AppRegistry 后运行系统检查 - Django Admin
【发布时间】:2021-07-14 13:31:35
【问题描述】:

我正在寻找进行特定检查,以确保项目中(多个应用程序中)使用的 Django 管理类(ModelAdmin、TabularInline 等)正在使用或继承自一个类(在这种情况下是一个 mixin) - 虽然系统检查会失败,因为 AppRegistry 尚未加载。

截至目前,我正在使用以下内容;虽然这会导致 AppRegistry 未加载。

from django.contrib.admin.sites import all_sites
from django.core.checks import register, Error

@register()
def check_django_admin_inheritance(app_configs, **kwargs):
    errors = []

    for admin_site in all_sites:
        for model, admin in admin_site._registry.items():
            if MyMixin not in admin.__class__.__bases__:
                errors.append(
                    Error('All admin sites should derive from the MyMixin (common.django_admin)',
                          hint='Inherit from MyMixin or use our custom ModelAdmin (common.django_admin)',
                          obj=admin, id="id-here")
                )

    return errors

有没有其他方法可以解决这个问题;除了 AppConfig.ready() 之外,这需要我将它放在每个应用程序中 - 我更希望找到一个干净且集中的解决方案。

【问题讨论】:

    标签: python python-3.x django django-admin


    【解决方案1】:

    您可以简单地将您的支票AppConfig.ready() 的某个合适的应用程序中注册。你还写了errors.append([Error(...)]),这意味着你将一个错误列表附加到你应该返回的列表中,这会给你一个错误:

    from django.contrib.admin.sites import all_sites
    from django.core.checks import register, Error
    
    
    def check_django_admin_inheritance(app_configs, **kwargs):
        errors = []
    
        for admin_site in all_sites:
            for model, admin in admin_site._registry.items():
                if MyMixin not in admin.__class__.__bases__:
                    errors.append(
                        Error('All admin sites should derive from the MyMixin (common.django_admin)',
                              hint='Inherit from MyMixin or use our custom ModelAdmin (common.django_admin)',
                              obj=admin, id="id-here")
                    )
    
        return errors
    
    
    class MyAppConfig(AppConfig):
        ...
        
        def ready(self):
            register(check_django_admin_inheritance) # Register the check here
    

    我在自己的应用程序中编写了此代码,并且检查为auth 应用程序的UserGroup 提供了错误消息,因此可以按预期工作。

    【讨论】:

    • 你是不是把它放在apps.py 然后放在INSTALLED_APPS 中?因为我仍然收到错误:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
    • 我还从问题中删除了围绕 Error 的列表 - 这是我在问题中添加的示例的问题。
    • 假设你使用MyMixin中的模型,那会因为应用注册表没有准备好(AppRegistryNotReady)而导致异常
    • @JulianCamilleri 您可能仍然拥有您的原始代码。不要在其他任何地方注册支票,只需在应用程序的ready 方法中注册即可。如果您仍然收到错误,则可能来自其他地方(将您的 complete 回溯添加到问题中)。
    • 我设法找到了问题 - 我还没有代码 - 一切都很好,但是在函数之外导入模型 - 当然,这将在 @987654334 之前执行@ 已加载 - 似乎有效,谢谢!
    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2013-05-05
    • 2015-04-13
    • 2015-09-14
    • 2011-09-30
    • 2016-10-23
    相关资源
    最近更新 更多