Django admin is a very valuable tool for developers especially during the development phase. Normal way of registering a model to the admin is as below.

from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['field1','field2', 'field3']
    #any additional configurations
    
site.admin.register(MyModel,MyModelAdmin)

 

Four lines of code for a single model. Now consider the amount of repeated code required if you have 10 models in your app. It also require you to manually edit the field list when your model changes.   You can get the admin to update the field list automatically if you change the list_display  declaration as below.

 list_display = [f.name for f in yourmodel._meta.get_fields() if f.auto_created == False]

But you still have to update your admin.py  whenever you add a new model to the app. To automatically register all models in your app, you can use below code snippet. Remember to put it at the end of your admin.py so that your custom ModelAdmin classes will still work as usual.

def auto_register(model):
    #Get all fields from model, but exclude autocreated reverse relations
    field_list = [f.name for f in model._meta.get_fields() if f.auto_created == False]
    # Dynamically create ModelAdmin class and register it.
    my_admin = type('MyAdmin', (admin.ModelAdmin,), 
                        {'list_display':field_list }
                        )
    try:
        admin.site.register(model,my_admin)
    except AlreadyRegistered:
        # This model is already registered
        pass


from django.apps import apps
for model in apps.get_app_config('yourapp').get_models():
    auto_register(model)

 

If you  want the auto registration to work only during development(DEBUG mode), you can use the below snippet.

def auto_register(model):
    #Get all fields from model, but exclude autocreated reverse relations
    field_list = [f.name for f in model._meta.get_fields() if f.auto_created == False]
    # Dynamically create ModelAdmin class and register it.
    my_admin = type('MyAdmin', (admin.ModelAdmin,), 
                        {'list_display':field_list }
                        )
    try:
        admin.site.register(model,my_admin)
    except AlreadyRegistered:
        # This model is already registered
        pass


from django.apps import apps
from django.conf import settings
if settings.DEBUG:
    for model in apps.get_app_config('yourapp').get_models():
        auto_register(model)

 

Leave a Reply

Your email address will not be published. Required fields are marked *