Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26465

Addig form fields to a custom user model in django admin panel

I'm going through the django for beginners book, testing the code from the chapter 8 about the Custom user model. The goal is to add the field age in the auth user model by subclassing the AbstractUser model.

First we create out CustomUser in models.py

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

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

Then creating CustomUserCreationFrom and CustomUserChangeFrom in forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser

class CustomUserCreationFrom(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('age',)

class CustomUserChangeFrom(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = CustomUser
        fields = UserChangeForm.Meta.fields

And finally, the CustomUserAdmin in admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationFrom, CustomUserChangeFrom
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationFrom
    form = CustomUserChangeFrom
    model = CustomUser
    list_display = ['username', 'email', 'age', 'is_staff',]

admin.site.register(CustomUser, CustomUserAdmin)

And of course telling django about our custom auth model in settings.py:

AUTH_USER_MODEL = 'users.CustomUser'

Logged as a super user, and when trying to add a new user, there is no field age in the creation form.

enter image description here

Am I missing something?

Upvotes: 3

Views: 3538

Answers (1)

JV conseil
JV conseil

Reputation: 376

Thanks to Michael Herman for this answer: https://testdriven.io/blog/django-custom-user-model/

In CustomUserAdmin in admin.py you have to declare a fieldsets:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ('email', 'is_staff', 'is_active',)
    list_filter = ('email', 'is_staff', 'is_active',)

    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Permissions', {'fields': ('is_staff', 'is_active')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')}
        ),
    )

    search_fields = ('email',)
    ordering = ('email',)


admin.site.register(CustomUser, CustomUserAdmin)

Upvotes: 6

Related Questions