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.
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
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)
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.
Broaden your backend architecture, REST API design, and production engineering expertise:
Implement login and registration forms using the custom user model.
Manage permissions on custom user models with PermissionsMixin.
Register custom users with UserAdmin to properly hash passwords.
Explain AbstractUser vs AbstractBaseUser in technical interviews.