Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 77 ยท Authentication and Security

Custom User Models

Replace Django's default User model the right way: AbstractUser vs AbstractBaseUser, AUTH_USER_MODEL, email login, a custom manager and why to decide early.

Django's built-in User is fine for many projects, but sooner or later someone asks for "log in with your email address", a phone number, a birthday or a role field. At that point you need your own user model. The Django documentation gives one strong piece of advice: create a custom user model at the start of every project, even if it is identical to the default. This lesson shows why, and how to do it properly.

You will build two custom models. The first extends AbstractUser with extra fields. The second uses AbstractBaseUser with an email address as the login name and its own manager. Both run live. The page writes a tiny accounts app into a temporary in-memory folder, exactly the structure startapp accounts creates on your computer.

Why decide at the start

Almost every table that refers to a user points at the user table with a foreign key. Migrations record that dependency. If you start with auth.User and switch to your own model later, Django cannot rewrite those foreign keys and the migration history for you; you end up editing migrations by hand and moving data between tables, usually on a database that already has real users.

If you begin with a custom model that simply extends AbstractUser and adds nothing, the switch costs you one small class. Later, adding an email login or a field is an ordinary migration.

flowchart TD
    A["New project?"] -->|"yes"| B["Create accounts app<br/>+ custom User from day one"]
    A -->|"no, it already uses auth.User"| C["Need only extra data?"]
    C -->|"yes"| D["Add a Profile model<br/>(OneToOneField to User)"]
    C -->|"no, need to change login or fields"| E["Plan a careful migration<br/>to a custom User"]
    B --> F["AbstractUser: keep Django's fields,<br/>add more"]
    B --> G["AbstractBaseUser: full control,<br/>write fields and manager"]

Start with a custom model. If the project already exists, a profile table is the safe way to add data; replacing the model is a migration project of its own.

Option 1: AbstractUser

AbstractUser is the complete default user: username, password, names, email, flags, permissions. You subclass it and add what you need. Nothing else changes: create_user(), the admin, forms and the login views all keep working.

Then you tell Django to use it with a single setting, AUTH_USER_MODEL = "accounts.User" (app label and model name). From then on:

  • Use get_user_model() in code that runs after startup (views, forms, tests).
  • Use settings.AUTH_USER_MODEL (a string) for foreign keys and other relations in models, so importing the user class is never needed at import time.
  • Never import django.contrib.auth.models.User directly in a project that has swapped it.
Python A custom user with AbstractUser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The user table now has bio and birth_year next to the usual columns, Post.author points at it through the setting, and the original auth.User refuses to work. That last error is Django protecting you from importing the wrong class.

Option 2: AbstractBaseUser

AbstractBaseUser gives you only the authentication core: a hashed password, last_login, set_password() and check_password(). Everything else is yours to define. Use it when the login name should not be a username, or when you want none of the default fields.

You must provide:

  • A field to log in with, named by USERNAME_FIELD. It has to be unique=True.
  • REQUIRED_FIELDS, the extra fields that createsuperuser asks for (the login field and password are always asked, so do not list them).
  • A manager with create_user() and create_superuser(), usually based on BaseUserManager. It must hash the password with set_password() and normalize the email with normalize_email().
  • is_active (and is_staff if you use the admin). Add PermissionsMixin to get is_superuser, groups and has_perm(); without it, permissions do not work.
Python Email login with AbstractBaseUser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the two authenticate() calls. The default ModelBackend reads the login from the keyword named like USERNAME_FIELD, so email=... works, and the generic username= keyword also works because login forms (such as AuthenticationForm) always call it username regardless of what it holds. Only the domain part of the email is lowercased by normalize_email(), because the local part may be case-sensitive in theory.

Migrations and the admin

Two practical rules for a real project:

  1. Run makemigrations accounts before the first migrate. The user model must exist in the very first migrations, because other apps depend on it. Create the app and set AUTH_USER_MODEL before you migrate for the first time.
  2. Register the model with the admin using UserAdmin. Subclassing django.contrib.auth.admin.UserAdmin gives you the password-change form and the permission widgets. For a custom AbstractBaseUser you also override fieldsets, add_fieldsets, list_display and ordering so they name your fields instead of username.
Python
# accounts/admin.py (read-only sketch)
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User


@admin.register(User)
class EmailUserAdmin(UserAdmin):
    ordering = ["email"]
    list_display = ["email", "display_name", "is_staff"]
    fieldsets = [
        (None, {"fields": ["email", "password"]}),
        ("Profile", {"fields": ["display_name"]}),
        ("Permissions", {"fields": ["is_active", "is_staff", "is_superuser", "groups", "user_permissions"]}),
    ]
    add_fieldsets = [(None, {"classes": ["wide"], "fields": ["email", "display_name", "password1", "password2"]})]
    search_fields = ["email"]

Keep the user model small. Authentication data (email, password, flags) belongs on the user; large or optional profile data (avatar, address, preferences) is better in a separate Profile model linked with a OneToOneField. That keeps the most-queried table light and the migration history simple.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Django recommend a custom user model at the start of a project?

    Foreign keys to the user and the migration history make a later swap painful. Starting with a custom model, even an empty subclass of AbstractUser, leaves room to change it easily.
  2. 2. How should a model refer to the user model in a ForeignKey?

    settings.AUTH_USER_MODEL is a string like 'accounts.User', resolved lazily. get_user_model() cannot be called while models are still loading, and the built-in User import breaks when the model is swapped.
  3. 3. Which two things does a custom AbstractBaseUser need so that createsuperuser and the admin work?

    createsuperuser reads USERNAME_FIELD and REQUIRED_FIELDS and then calls create_superuser() on the manager. The admin additionally needs is_staff and is_active on the model.
  4. 4. What does PermissionsMixin add to a custom user?

    Without PermissionsMixin, a custom AbstractBaseUser has no groups, no user permissions and no has_perm() support. AbstractUser already includes it.

Summary

  • Decide on a custom user model before the first migration; subclass AbstractUser if you only need extra fields.
  • Use AbstractBaseUser (plus PermissionsMixin) when you need a different login field such as email.
  • Set AUTH_USER_MODEL = "app.Model"; use settings.AUTH_USER_MODEL in relations and get_user_model() in code.
  • A custom manager must hash passwords with set_password() and implement create_user() and create_superuser().
  • USERNAME_FIELD is the unique login field; REQUIRED_FIELDS lists the extra prompts for createsuperuser.
  • Register the model with a UserAdmin subclass; keep big optional data in a separate profile model.

Next up: Permissions, Groups and Authorization.