Slimming down your project's admin
Django | 2008-10-08 |
Speaking of slimming down, I was just at the gym, listening to the most recent episode of This Week in Django on my iPod (not exactly the best workout motivation, but it was what I had with me at the time). In this week's episode, Brian Rosner mentions a tip from Rob Hudson, and that is that you can register a model in a project's admin without writing an admin class down at the app level. Apparently that's been possible all along, it was only just added to the Django documentation.
So, for example, let's say you start with a project admin that looks like this:
from django.contrib import admin
from blog.pages.admin import CategoryAdmin, ContentAdmin
from blog.pages.models import Category, Content
class AdminSite(admin.AdminSite):
pass
site = AdminSite()
site.register(Category, CategoryAdmin)
site.register(Content, ContentAdmin)
And down in your application, you have a few classes that look like this:
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'active', 'created_at',)
class ContentAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
You can do something like this in your project admin:
from django.contrib import admin
from blog.pages.models import Category, Content
class AdminSite(admin.AdminSite):
pass
site = AdminSite()
site.register(Category)
site.register(Content, prepopulated_fields = {"slug": ("title",)})
And down at the app level, well, you can do away with those other classes altogether.
If you don't set any list_display values, it looks like the admin will default to the generic object name. So be sure to define a unicode method, or you'll end up with a whole page full of "Content Object, Content Object, Content Object", blah blah blah.