Django Custom User Model: AbstractUser & Email-Based Authentication

In almost every modern web service, users log in with their email address rather than an arbitrary username. While Django ships with a default auth_user model, setting up a Custom User Model at the inception of your project is an absolute industry best practice.

Building an Email-First Custom User Model with AbstractUser

Create an accounts app and define your user model subclassing AbstractUser:

# accounts/models.py
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models

class CustomUserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email address must be provided.')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)  # Securely hashes password via PBKDF2
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractUser):
    # Remove username field completely
    username = None
    email = models.EmailField('Email Address', unique=True)
    
    # Custom business profile fields
    full_name = models.CharField(max_length=150, blank=True)
    bio = models.TextField(blank=True)
    phone_number = models.CharField(max_length=20, blank=True)

    # Use email as primary authentication identifier!
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']  # Prompted on createsuperuser

    objects = CustomUserManager()

    def __str__(self):
        return self.email

Registering in settings.py & Admin

Point Django to your custom model inside settings.py:

# mywebsite/settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'

Register it in accounts/admin.py using Django's UserAdmin to ensure password hashing works in the admin interface:

# accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    list_display = ('email', 'full_name', 'is_staff', 'is_active')
    list_filter = ('is_staff', 'is_active')
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal Info', {'fields': ('full_name', 'bio', 'phone_number')}),
        ('Permissions', {'fields': ('is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )
    ordering = ('email',)

admin.site.register(CustomUser, CustomUserAdmin)

Crucial Pre-Migration Warning

Always set AUTH_USER_MODEL BEFORE running your very first python manage.py migrate! If you migrate with the default user model and try to change it later, foreign key tables in django.contrib.admin will reference the wrong table, requiring tedious manual database manipulation.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why does the official Django documentation strongly recommend creating a custom user model at the start of every project?

Django's default user model (`django.contrib.auth.models.User`) has a rigid schema (username required, limited profile fields). Once migrations run and foreign keys reference `auth_user`, migrating to a custom user model later requires complex manual database schema operations. Creating a custom user model upfront gives you future-proof flexibility with zero pain.

Q2. What is the difference between AbstractUser and AbstractBaseUser?

`AbstractUser` retains all default Django user fields (username, first_name, last_name, is_staff, is_active, permissions), allowing you to add extra fields or change the username field. `AbstractBaseUser` provides only the bare minimum password hashing and session tracking, requiring you to define all fields and managers from scratch.

Q3. How do you configure Django to use your custom user model?

Add `AUTH_USER_MODEL = 'accounts.CustomUser'` to your `settings.py` file before running the initial database migrations.

Q4. How should other models reference the user model?

Always use `settings.AUTH_USER_MODEL` (e.g. `author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)`). In runtime Python code, use `from django.contrib.auth import get_user_model; User = get_user_model()`.

Explore Related Django Tutorials & Next Steps

Broaden your backend architecture, REST API design, and production engineering expertise:

User Authentication & Logins

Implement login and registration forms using the custom user model.

Permissions & Groups (RBAC)

Manage permissions on custom user models with PermissionsMixin.

Django Admin Customization

Register custom users with UserAdmin to properly hash passwords.

130+ Django Interview Questions

Explain AbstractUser vs AbstractBaseUser in technical interviews.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!