Julian Camilleri
Julian Camilleri

Reputation: 3125

Running a system check after AppRegistry is initialized - Django Admin

I'm looking to run a specific check, to make sure that Django Admin classes (ModelAdmin, TabularInline etcetera) used within the project (within multiple apps) are using or inheriting from a class (a mixin in this case) - although a system check would fail since the AppRegistry is not yet loaded.

I'm using the below as of current; although this raises that the AppRegistry is not loaded.

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

Is there any other way around this; besides the AppConfig.ready() which would require that I place it in every application - I'm more looking towards a solution that is clean and centralized.

Upvotes: 1

Views: 180

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21812

You can simply register your check inside the AppConfig.ready() of some suitable app. Also you write errors.append([Error(...)]) which means you append a list of errors to the list you are supposed to return which will give you an 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

I write this in my own app, and the check gives an error message for User and Group of the auth app, so this works as intended.

Upvotes: 2

Related Questions