Automatically register all Django models in Django admin

Photo of Tom Dekan
by Tom Dekan
Updated: Fri 03 May 2024

Manually creating an Django admin entry for every new model is a waste of time. Let's do it automatically

Create function to register all models

  • We call this function after registering any custom admin classes.
  • uses Django's inbuilt get_models() function to register every model in your project register
  • ignore the LogEntry, ContentType, Session, and Token (inbuilt django models)
from django.apps import apps
from django.contrib import admin


def register_all_app_models():  
   """  
   Register any unregistered app models. We call this function    after registering any custom     admin classes.  
    """    
   models_to_ignore = [  
       'admin.LogEntry',  
       'contenttypes.ContentType',  
       'sessions.Session',  
       'authtoken.TokenProxy',  
       'authtoken.Token',  # We automatically register the authtoken app models.  
   ]  
   for model in apps.get_models():  
       try:  
           if model._meta.label in models_to_ignore:  
               continue  
           else:  
               class modelAdmin(admin.ModelAdmin):  
                   list_display = [field.name for field in model._meta.fields]  

               admin.site.register(model, modelAdmin)  
       except admin.sites.AlreadyRegistered:  
           pass

Add it to your admin.py file

  • Register the generated models with admin.site.register().
  • We handle the AlreadyRegistered exception by passing it -ignoring any models that are already registered.
# admin.py

class CreationAdmin(admin.ModelAdmin): # Example specific model admin class.
   list_display = ["id", "diffuser", "key", "hr_key", "created_at", "image_download_count"]
   list_filter = ["diffuser"]

admin.site.register(models.Creation, CreationAdmin)
register_all_app_models() # Call the function after registering any specific model admin class.

Let's get visual.

Do you want to create beautiful frontends effortlessly?
Click below to book your spot on our early access mailing list (as well as early adopter prices).
Copied link to clipboard 📋

Made with care by Tom Dekan

© 2024 Photon Designer