Customizing The Admin: Part 3
This entry in the "Customizing The Admin" mini-series is a basically a quick tip but has tons of potential. The ModelAdmins that make up the admin area can take many arguments to customize the how admin works, but the most flexible of these is the form option. You can use this to override the default behavior, which is to use a ModelForm for model the ModelAdmin is registered with, by providing your own form instead. An example:
from django.contrib import admin
from django.core.cache import cache
from django import forms
from blog.models import Post
class CachedPostForm(forms.ModelForm)
class Meta:
model = Post
def save(self):
post = super(CachedPostForm, self).save()
# This could also be done by overriding the model's save method,
# via a post_save signal or in the view on accessing the post.
# Equally, the cache_key should probably be generated in the model
# so that it can be accessed elsewhere without code duplication.
cache_key = "posts:%s" % post.id
cache.set(cache_key, post, 3600)
class PostAdmin(admin.ModelAdmin):
form = CachedPostForm
list_display = ('title', 'tease', 'author', 'created')
search_fields = ('title', 'content')
admin.site.register(Post, PostAdmin)
The form you provide should be a subclass of ModelForm (which extends Form so any Form tricks will work) or bad things can happen. You can use this technique to add validation, provide additional custom processing, verify/maintain data integrity, et cetera.
Sorry, comments have been closed on this post.
1 Comment
Maybe as an idea for part 4 :) .. you know of some way to override the list_display and search_fields so they can also be set based on request.user. The admin now allows access to request.user for queryset etc but it's not obvious to a new person how the same can be done for those options .. and it would be quite useful to show and hide the changelist columns based on it. The example in your part 2 indicates it can be done but it's not clear which bits are necessary for this particular scenario.
Again thanks.