Edit related field on the edit page of the parent model

My Profile model has a OneToOne field with User model.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verified = models.BooleanField(default=False)

And ModelAdmin is defined as below:

class UserAdmin(UserAdmin):
    fieldsets = (
    ....
    ....
        ('Permissions'),
            'fields': (
                'is_active',
                'is_staff',
                'is_superuser',
    ....
    ....

Is it possible to add verified filed to the above (after is_superuser for example) so I can edit it in the same page as the rest of the User model?

P.S: I've already managed to add it to list_display and list_filter of User.

you can use override AbstractUser from model Django so you can merge user in one place like this:


from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
   verified = models.BooleanField(default=False)

and you need to add this line to Django settings.py file so that Django knows to use the new User class:


AUTH_USER_MODEL = 'users.CustomUser'

then make sure to migrate :


(env)$ python manage.py makemigrations
(env)$ python manage.py migrate

User model Extension vs Inheritance.

Your profile model only add some elements to user. In this case Model inheritance can be better.

# models.py
class Profile(user):
    verified = models.BooleanField(default=False)

after that you can achieve all fields for user and for profile:

# admin.py
class ProfileAdmin(ModelAdmin):
    fields = '__all__'

if you don't want to switch on Model inheritance.

You can use InlineModel in UserAdmin to change related model.

# admin.py
class ProfileInline(StackedInline):
    model=Profile

class UserAdmin(ModelAdmin):
    inlines = (ProfileInline, )

OP can use one of the InlineModelAdmin objects such as StackedInline. This allows one to create inline forms providing one the ability to edit models on the same page as a parent model.

Adapting for OP's case, it would be something like

from django.contrib import admin

class ProfileInline(admin.StackedInline):
    model = Profile

class UserAdmin(admin.ModelAdmin):
    inlines = [
        ProfileInline,
    ]

admin.site.register(User, UserAdmin)

Now OP's admin site is set up to edit Profile objects inline from the User detail page.

Back to Top