🔐 Django Authentication : Mini Series
✅ Part 1: How to Customize the Django User Model
This is Part 1 of our Django Authentication Mini-Series.
Next up: Email Verification → User Profiles → Password Reset
🔐 How to Customize the Django User Model in Django (Step-by-Step)
Introduction
While Django’s built-in User
model works for many use cases, real-world apps often require custom fields like full name, phone number, or even profile images. Instead of modifying the default model (which can be tricky later), Django allows you to create your own user model from the beginning.
In this post, you'll learn how to build and use a custom user model in Django — safely and properly.
Step 1: Start a New Project or App
⚠️ This should be done before applying migrations if you're starting from scratch.
django-admin startproject myproject
cd myproject
python manage.py startapp accounts
Step 2: Create a Custom User Model
In accounts/models.py
:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
full_name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
objects = CustomUserManager()
def __str__(self):
return self.email
Step 3: Update settings.py
In your myproject/settings.py
:
AUTH_USER_MODEL = 'accounts.CustomUser'
This tells Django to use your custom model instead of the default one.
Step 4: Create & Apply Migrations
Only do this if you haven't applied migrations yet (new project):
python manage.py makemigrations
python manage.py migrate
Step 5: Update admin.py
(Optional but Useful)
In 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')
search_fields = ('email',)
ordering = ('email',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal Info', {'fields': ('full_name',)}),
('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'groups', 'user_permissions')}),
('Dates', {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'full_name', 'password1', 'password2', 'is_staff', 'is_active')}
),
)
admin.site.register(CustomUser, CustomUserAdmin)
Step 6: Use Custom User in Forms
Replace any UserCreationForm
or AuthenticationForm
with ones adapted to use CustomUser
.
Example:
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('email', 'full_name')
Conclusion
You’ve now created a fully customizable authentication model that supports your project’s future needs. With this foundation, you can:
-
Add new fields anytime
-
Use email instead of usernames
-
Extend it easily in the next posts (user profiles, email verification, etc.)
Next in this mini-series:
📧 Add Email Verification to Django Signup
No comments:
Post a Comment