Add fields from another model to the admin site

Viewed 38

My Profile model has a OneToOne relation with Django's built-in User model.

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

If I want to change user's password or properties like Active or Superuser I have to do it in one Change User page, and to edit verified property I have to go to another.

Is there any way to merge this:

enter image description here

And this:

enter image description here

Into one form so I can edit everything about a user in one page?

2 Answers

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, )

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
Related