Displaying Custom User Profile Fields In Django’s Admin

Dec. 6, 2008

10:02 am

After following James Bennett's 2006 article on extending Django's User model, I was surprised to find that the resulting profile fields didn't automagically appear in the admin panel. I knew it had to be possible. The solution just took some sleuthing.

A very brief explanation.

For those of you who haven't toyed around much with Django, all we're talking about is the ability to take the framework's built-in User system – which has all sorts of authentication shortcuts and permissions goodies baked in – and add an arbitrary number of extra fields. Profile information, if you will. Super handy stuff.

The solution.

It turns out the solution was hiding inside a still unanswered question posited on the Google Groups message boards.

Assuming an app called "users" with an auth profile module called UserProfile (as in James Bennett's tutorial linked above), your admin.py for the users app would look like this:

  1. from django.contrib import admin
  2. from django.contrib.auth.models import User
  3. from django.contrib.auth.admin import UserAdmin
  4. from website.users.models import UserProfile
  5.  
  6. admin.site.unregister(User)
  7.  
  8. class UserProfileInline(admin.StackedInline):
  9. model = UserProfile
  10.  
  11. class UserProfileAdmin(UserAdmin):
  12. inlines = [UserProfileInline]
  13.  
  14. admin.site.register(User, UserProfileAdmin)

For me, the big news is in that sixth line. The unregister method on the site object is what lets us override the default behavior of the admin panel for built-in apps. I can see this being of use with other bundled apps – think flatpages or comments.

Comments

May 1, 2009

9:38 am

Thanks for the tip mate.

John (#)

June 1, 2009

5:26 pm

good tip. just what i wanted

tuza (#)

June 4, 2009

4:22 pm

works like a charm

tip (#)

June 13, 2009

2:50 am

Great thing! Thanks for this.

Naos (#)

July 10, 2009

4:33 am

Wouldn’t expect it to be that easy actualy. Pretty nice, thanks for that, I sure could use it.

Stancje (#)

September 14, 2009

7:23 am

thanks..

cet (#)

October 15, 2009

8:33 am

Wow, that was an outstanding tip and a fantastic timesaver today.  Thanks so much!  This info should be in the Django manual, right in the section where they talk about user profiles.  It’s the missing link.

Thanks Matt.

O'Shaughnessy Evans (#)

Whaddya think?