Login

Type less with newforms admin

Author:
ncw
Posted:
July 26, 2008
Language:
Python
Version:
.96
Score:
-4 (after 6 ratings)

I recently converted a site with over 60 models to newforms admin. I like the seperation of the display from the defintion, but it does introduce quite a bit more typing which isn't in the spirit of Django DRY...

I particular I got bored of typing

admin.site.register(Model, ModelAdmin)

Over and over again so I wrote this little bit of code which does a bit of introspection. It assumes that

  1. You import all your models into your admin.py, ie from "myapp.models import *"
  2. The admin class for Model is called ModelAdmin

Put this snippet at the end of your admin.py

I hope that saves someone a bit of typing!

1
2
3
4
5
# Register Model with ModelAdmin
for name, model_admin in globals().copy().iteritems():
    if name.endswith("Admin"):
        model = globals()[name[:-5]]
        admin.site.register(model, model_admin)

More like this

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

Comments

aarond10ster (on July 27, 2008):

Ummm...

class MyModel:
    ...
    class Admin:
         pass

Is this too hard to do? It does involve an extra 20 characters per model but gives you freedom to customise as needed later on and explicitly states whats going on.

#

jho406 (on July 30, 2008):

@aarond10ster

Your referring to old-forms admin. Django 1.0 alpha uses newforms-admin and has completely decoupled admin from the models.

#

Please login first before commenting.