Django Shortcut: Automated Admin Model Registration

2009-11-28

As we all know, Django has a rather lovely admin package. However, in a module’s admin.py, all desired models must manually be registered with django.contrib.admin.site.register.

No longer, say I. The only time I use the admin package is during development, I roll my own for production. So, it stands to reason that I wouldn’t want to spend much time registering models with admin, especially if I’m going to be changing the models around!

And so, as the cliché goes: without further ado, I present my snippet:

1# Change to import the proper model object 2from package import models 3 4# Leave alone 5from django.db.models.base import ModelBase 6from django.contrib import admin 7from inspect import getmembers 8 9for model in getmembers(models): 10 if type(model[1]) == ModelBase: # model[1] is the actual object 11 admin.site.register(model[1])

The primary downside with this is that there’s a lack of customization. Although, as I said, I use the admin views only for development, so customization is most often not a concern of mine.

← all posts

michael schade

I like learning new things. Previously: Kenchi founder, eng & ops teams at Stripe from 2012-2019. Say hi! 🏳️‍🌈