"""
admin.py
Auto-register admin classes based on models in your project
Questions? email: dodgyville@gmail.com
"""
from django.contrib import admin
from django.db import models as dmodels
from myproject import models
#get the models from myproject.models]
mods = [x for x in models.__dict__.values() if issubclass(type(x), dmodels.base.ModelBase)]
admins = []
#for each model in our models module, prepare an admin class
#that will edit our model (Admin<model_name>, model)
for c in mods:
admins.append(("%sAdmin"%c.__name__, c))
#create the admin class and register it
for (ac, c) in admins:
try: #pass gracefully on duplicate registration errors
admin.site.register(c, type(ac, (admin.ModelAdmin,), dict()))
except:
pass
Comments
You don't need to do this. admin.site.register works if you just pass it in a model with no modeladmin, provided you are OK with the default settings:
admin.site.register(BlogPost)
If you just want to set a couple of options you don't need to create a ModelAdmin class either - you can pass them directly to register as kwargs as of changeset 8063:
admin.site.register(BlogPost, list_display = ('headline', 'publish_date'))
You only need to create a ModelAdmin subclass if you want to over-ride actual methods, such as the queryset() method to customise which objects show up on the changelist page.
#
This still avoids having to type:
admin.site.register()
if you have lots of models...
#
d'oh, my markup was removed from last post! haha
should be: admin.site.register(your_model_name)
#