← Back to Django, page 2

django-0025 · Medium mid

Why should you set up a custom user model at the start of a Django project, and how do you do it?

Changing AUTH_USER_MODEL after the first migration is hard because every foreign key to the user table is tied to it. Starting with class User(AbstractUser) and AUTH_USER_MODEL = "accounts.User" costs nothing and lets you add fields like phone or roll number later. Refer to the user through settings.AUTH_USER_MODEL in models and get_user_model() in code.

Full answer

Django's default auth.User works, but projects often need changes later: log in with email, add a phone number, a role, or a student roll number. Once migrations have created auth_user and other tables point at it, switching to a different model means rewriting foreign keys and migrating data by hand. The Django docs strongly recommend a custom user model for every new project.

Setup, before the first migrate:

python
# accounts/models.py
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    phone = models.CharField(max_length=15, blank=True)

# settings.py
AUTH_USER_MODEL = "accounts.User"

Then register it in the admin (admin.site.register(User, UserAdmin)), and run makemigrations and migrate.

Choosing a base:

  • AbstractUser: keeps username, names, email, staff flags and permissions. Add fields. The usual choice.
  • AbstractBaseUser + PermissionsMixin: start almost from scratch (only password and last_login). Use it for email-only login or a very different identity model. You must write a manager with create_user and create_superuser, and set USERNAME_FIELD and REQUIRED_FIELDS.

Referring to the user:

  • In model fields: models.ForeignKey(settings.AUTH_USER_MODEL, ...), never User imported directly.
  • In code: get_user_model().

Profile model vs custom user: extra data that only some features need (a teacher's subject list) can live in a separate Profile with a OneToOneField. Data needed on every request or for login belongs on the user model.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth.models import AbstractUser, Group, Permission
from django.db import models, connection


class User(AbstractUser):
    phone = models.CharField(max_length=15, blank=True)
    roll_no = models.CharField(max_length=12, blank=True)

    # Two user models exist in this demo (auth.User and this one), so the
    # reverse names below must not clash. A real project only has one.
    groups = models.ManyToManyField(Group, blank=True, related_name="school_users")
    user_permissions = models.ManyToManyField(Permission, blank=True, related_name="school_users")

    class Meta:
        app_label = "school"


class Loan(models.Model):
    member = models.ForeignKey("school.User", on_delete=models.CASCADE, related_name="loans")
    book = models.CharField(max_length=60)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (User, Loan):
        editor.create_model(m)

u = User.objects.create_user("tara", password="Library#2026", phone="98xxxxxx01", roll_no="BCA-17")
Loan.objects.create(member=u, book="Ignited Minds")
print(u.username, u.phone, u.roll_no, u.check_password("Library#2026"))
print([l.book for l in u.loans.all()])
print([f.name for f in User._meta.get_fields() if f.name in ("phone", "roll_no", "is_staff")])

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a real project AUTH_USER_MODEL points to this class and auth.User is not used; the related_name overrides exist only because both models live in one demo file. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): tara 98xxxxxx01 BCA-17 True ['Ignited Minds'] ['is_staff', 'phone', 'roll_no']

Key points

  • Set AUTH_USER_MODEL before the first migration
  • AbstractUser for adding fields, AbstractBaseUser for full control
  • Use settings.AUTH_USER_MODEL in ForeignKeys
  • Use get_user_model() in code
  • Profile models suit optional per-feature data

Common mistakes

  • Starting with auth.User and trying to swap it after production data exists
  • Importing User directly in ForeignKeys instead of settings.AUTH_USER_MODEL
  • Using AbstractBaseUser without writing a proper manager
  • Forgetting to register the custom user with UserAdmin

Follow-ups

  • How would you make email the login field?
  • How would you migrate an existing project from auth.User to a custom model?
  • When is a Profile model better than adding fields to User?

Tips

  • Say why it must happen before the first migration
  • Compare AbstractUser and AbstractBaseUser
  • Mention settings.AUTH_USER_MODEL and get_user_model()