Autogenerate admin classes in admin.py

 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: 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

More like this

  1. easy admin registration by alia_khouri 5 years, 7 months ago
  2. admin.py generator from a model by tamonashroy 4 years, 2 months ago
  3. Type less with newforms admin by ncw 5 years, 9 months ago
  4. Generate newforms-admin admin.py file by NL 6 years, 2 months ago
  5. Export Related as JSON Admin Action by johnboxall 4 years, 9 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([HTML_REMOVED])

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)

#

(Forgotten your password?)