Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: check for modeladmin for a given model

How does one check to see if a modeladmin exists for a given model?

modeladmins are created by registering a model with the admin.site object. how can one check the site object to see which models have been registered, and with which admin_class?

like image 752
Cody Django Avatar asked Jun 02 '10 07:06

Cody Django


2 Answers

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

like image 27
hashlash Avatar answered Sep 19 '22 19:09

hashlash


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>
like image 155
Daniel Roseman Avatar answered Sep 20 '22 19:09

Daniel Roseman