Login

Autogenerate admin classes in admin.py

Author:
dodgyville
Posted:
August 22, 2008
Language:
Python
Version:
.96
Score:
-1 (after 1 ratings)

Tired of adding admin classes to admin.py whenever you add a model? This admin.py automatically keeps itself up-to-date with your models.py file.

It assumes if you have a model: MyModel, you want an admin class called AdminMyModel.

Regards, Luke Miller

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""
admin.py
Auto-register admin classes based on models in your project
Questions? email: [email protected]
"""
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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

simon (on August 22, 2008):

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.

#

dodgyville (on August 23, 2008):

This still avoids having to type:

admin.site.register(<eachModel>)

if you have lots of models...

#

dodgyville (on August 23, 2008):

d'oh, my markup was removed from last post! haha

should be: admin.site.register(your_model_name)

#

Please login first before commenting.