Search code examples
djangodjango-admindjango-users

How do I inline edit a django user profile in the admin interface?


If you want to store extra information about a user (django.contrib.auth.models.User) in Django you can use the nifty AUTH_PROFILE_MODULE to plug in a "profile" model. Each user then gets a profile. It's all described here:

Now, let's say I have created an application called accounts with a model called UserProfile and registered it as the profile model for my users. How do I inline the editing of the profile in the admin interface for editing users (or vice versa)?


Solution

  • Well, it turns out that this is quite easy, once you know how to do it. This is my myapp/accounts/admin.py:

    from django.contrib import admin
    from myapp.accounts.models import UserProfile
    from django.contrib.auth.models import User
    
    class UserProfileInline(admin.StackedInline):
        model = UserProfile
        max_num = 1
        can_delete = False
    
    class AccountsUserAdmin(admin.UserAdmin):
        inlines = [UserProfileInline]
    
    # unregister old user admin
    admin.site.unregister(User)
    # register new user admin that includes a UserProfile
    admin.site.register(User, AccountsUserAdmin)
    

    The default admin.UserAdmin ModelAdmin class for users is unregistered and a new one specifying an inline UserProfile is registered in its place. Just thought I should share.