Create Custom UserModel

Hi. I’m new to Django and I try to create custom user.
Here is my code.
Django version: Django==5.1.4
App name: accounts.
config/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]

AUTH_USER_MODEL = 'accounts.CustomUser'

accounts/models.py

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

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

accounts/form.py

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

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

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

accounts/admin.py:

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

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


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationFrom
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username', 'email', 'age', 'is_staff']
    fieldsets = UserAdmin.fieldsets + (
        (
            None,
            {'fields': ('age', )},
        ),
    )
    add_fieldsets = UserAdmin.add_fieldsets + (
        (
            None,
            {'fields': ('age', )},
        ),
    )

admin.site.register(CustomUser, CustomUserAdmin)

after makemigration accounts app and migrate all apps, I get this error (for creating new user):

Welcome @mlsoheyl !

Side note: Please avoid posting screenshots for textual information. In the case of the error summaries being shown in the browser, it’s better if you posted the complete error message and traceback from the runserver console. (And also enclose that text between lines of ```.)

For the issue you’re asking about, see the threads at:

1 Like