>

Jul 19, 2012

Extending django user admin model with custom data

Extending django user model is pretty weird and not clearly understandable, especially when you wanna edit user profile via standard django user admin form. Solution for this is very simple, just read below.

Django documentation points to the AUTH_PROFILE_MODULE setting. Using this option will allow you to link your custom model with user object, but you will not have ability to modify this model via django admin user form.

I've found an easy way for adding additional user data to the user model without using AUTH_PROFILE_MODULE setting. Sure you can still use this option but it with my code without any problem.

How to add additional data to user admin model

First of all you'll need to create your custom model with OneToOne relation to the user model somewhere in models.py:
from django.db import models

class UserProfile(models.Model):

    # Link to the user model
    user = models.OneToOneField(User, related_name='profile', unique=False)

    # Any oter data you'll like
    has_somwere_access = models.BooleanField(u"Access", default=False, blank=True)

Next you'll need to re register your user model admin somewhere in admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as OriginalUserAdmin
from your.userprofile.models import UserProfile

class UserProfileInline(admin.StackedInline):
    """ As you are noticed your profile will be edited as inline form """
    model = UserProfile
    can_delete = False

class UserAdmin(OriginalUserAdmin):
    """ Just add inlines to the original UserAdmin class """
    inlines = [UserProfileInline, ]

try:
    admin.site.unregister(User)
finally:
    admin.site.register(User, UserAdmin)
And that is all you need. Good luck.