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

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


I propse a slightly improved version of André's solution as it breaks the list view in /admin/auth/user/:

from django.contrib import adminfrom member.models import UserProfilefrom django.contrib.auth.models import Userfrom django.contrib.auth.admin import UserAdmin as AuthUserAdminclass UserProfileInline(admin.StackedInline): model = UserProfile max_num = 1 can_delete = Falseclass UserAdmin(AuthUserAdmin): inlines = [UserProfileInline]# unregister old user adminadmin.site.unregister(User)# register new user adminadmin.site.register(User, UserAdmin)


I propose another improvement to Robert's solution:

from django.contrib import adminfrom member.models import UserProfilefrom django.contrib.auth.models import Userfrom django.contrib.auth.admin import UserAdmin as AuthUserAdminclass UserProfileInline(admin.StackedInline):   model = UserProfile   max_num = 1   can_delete = Falseclass UserAdmin(AuthUserAdmin):   def add_view(self, *args, **kwargs):      self.inlines = []      return super(UserAdmin, self).add_view(*args, **kwargs)   def change_view(self, *args, **kwargs):      self.inlines = [UserProfileInline]      return super(UserAdmin, self).change_view(*args, **kwargs)# unregister old user adminadmin.site.unregister(User)# register new user adminadmin.site.register(User, UserAdmin)

Without this change to UserAdmin, the custom UserProfileInline section will show up on the "add user" screen, which is just supposed to ask for the username and password. And if you change any of the profile data on that screen (away from the defaults) before you save, you'll get a "duplicate key" database error.


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 adminfrom myapp.accounts.models import UserProfilefrom django.contrib.auth.models import Userclass UserProfileInline(admin.StackedInline):    model = UserProfile    max_num = 1    can_delete = Falseclass AccountsUserAdmin(admin.UserAdmin):    inlines = [UserProfileInline]# unregister old user adminadmin.site.unregister(User)# register new user admin that includes a UserProfileadmin.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.