Customize admin for User model
Before django 1.0 I don’t remember that there was a way to customize how the admin renders the User overview. Fortunately 1.0 does allow it.
It took me a bit to figure out. After searching the web and the django docs I didn’t find it right away, so I tried the normal fallback: auto-completion (WingIDE does that really good).
Normally if you just define your own UserAdmin class in admin.py, like this:
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login')
search_fields = ['username', 'email']
admin.site.register(User, UserAdmin)
You get the following error when starting up the server:
django.contrib.admin.sites.AlreadyRegistered:
The model User is already registered
Well, as I said, the auto-completion just made me come across it pretty quickly, and it is so logical. Simply unregister the admin class for User before redefining it :-).
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login')
search_fields = ['username', 'email']
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Done. Cool, ha?
Congrats to all the people behind Django 1.0, good stuff!
Martin said,
September 15, 2008 at 1:29 pm
Small notice: You only get the \"AlreadyRegistered\" error if you use \"admin.autodiscover()\" which is disabled by default.
Wolfram said,
September 15, 2008 at 5:24 pm
@Martin: Uh thanks …
Peter Bengtsson said,
September 16, 2008 at 1:34 am
I noticed this too. The trick is to put all your model admin classes in a separate file called admin.py and at the top of it have the autodiscover() as Martin points out. Then you won\’t get the AlreadyRegistered errors.
Matthew said,
September 18, 2008 at 12:53 am
I think you\’ll have some issues with password management and perhaps a few other things if you don\’t inherit from \"django.contrib.auth.admin.UserAdmin\" instead of \"admin.ModelAdmin\". At least I did when I tried this.
slacy said,
November 16, 2009 at 8:52 pm
Thanks! This is exactly what I was looking for — this should be put into the Django tutorials or djangobook!