How to add CustomUser fields in admin?

For my project I have a CustomUser which has two new fields in it. When I go to the Admin page, these fields show when listing the Users. However, when I go to change a user, the only fields I can change are username, password, first name, last name and email address.
Models.py

class CustomUser(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_student = models.BooleanField('student status', default=False)
    is_teacher = models.BooleanField('teacher status', default=False)
    district = models.CharField(max_length=4, blank=True, default="SD39")

    def __str__(self):
        return self.username

admin.py

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = [
        'email', 'username', 'is_teacher', 'is_student', 'id',
    ]


admin.site.register(CustomUser, CustomUserAdmin)

forms.py

class CustomUserCreationForm(UserCreationForm):
    """ form from class based view """

    class Meta:
        model = get_user_model()
        fields = ('username', 'is_teacher', 'is_student', 'district')


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'is_teacher', 'is_student')

I’m using django-allauth but I don’t think there is anything in there that affects admin (other than a few things about email addresses).
Can the fields is_teacher and is_student be added to the change_view in admin?

I believe the problems are with using a custom user model, but inheriting a lot of functionality from the default User and UserAdmin classes.

I would recommend that your forms inherit directly from ModelForm, and your admin class inherit from ModelAdmin.

Briefly, your custom user model inherits from AbstractUser, not User (which is correct) - but those default admin classes and forms are built around User - which is a sibling in the inheritance hierarchy, not an ancestor. If there’s specific functionality you want from those objects, I’d recommend copying those parts of the code into yours, not try to inherit from them.

One easy way to add these is via an additional fieldset. E.g.

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    # everything else
    fieldsets = UserAdmin.fieldsets + (
        ('Custom Fields', {
            'fields': ('is_teacher', 'is_student')
        }),
    )

2 Likes