[Fixed]-Django: check for modeladmin for a given model

22👍

Interesting question, which provoked me to do a little digging.

Once the admin classes have been registered, they are stored in an attribute of the site object called – not surprisingly – _registry. This is a dictionary of model classes to modeladmin classes – note both the keys and values are classes, not names.

So if you have an admin.py like this:

from django.contrib import admin
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('field1', 'field2')

admin.site.register(MyModel, MyModelAdmin)

then once that has actually been imported – usually by the admin.autodiscover() line in urls.py – admin.site._registry will contain something like this:

{<class 'myapp.models.MyModel'>: 
    <django.contrib.admin.options.ModelAdmin object at 0x10210ba50>}

and you would get the ModelAdmin object for MyModel by using the model itself as the key:

>>> admin.site._registry[MyModel]
<django.contrib.admin.options.ModelAdmin object at 0x10210ba50>

3👍

Django’s django.contrib.admin.sites.AdminSite has a method for checking registered Model called .is_registered(model). This method will check on the admin site’s _registry attribute (just like Daniel Roseman‘s approach)

So, if you have files like these:

# models.py

from django.db import models

class MyModel(models.Model)
    field1 = ...
    field2 = ...
# admin.py

from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('field1', 'field2')

admin.site.register(MyModel, MyModelAdmin)

You could make some test like this:

# tests.py

from django.test import TestCase
from .models import MyModel

class TestModelAdmin(TestCase):

    def test_mymodel_registered(self):
        self.assertTrue(admin.site.is_registered(MyModel))

nb: I’ve checked it on the Django’s modules documentation from Django 1.8 to Django 2.2

Leave a comment