Using a custom user model lets you add extra fields or change how users work in your Django app. AbstractUser helps you start with Django's default user features and add your own.
0
0
Custom user model with AbstractUser in Django
Introduction
You want to add extra information to users, like phone number or birthdate.
You need to change the way users log in, like using email instead of username.
You want to keep Django's built-in user features but customize some parts.
You are starting a new project and want a flexible user model from the start.
Syntax
Django
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # Add extra fields here phone_number = models.CharField(max_length=15, blank=True, null=True) # In settings.py AUTH_USER_MODEL = 'yourapp.CustomUser'
You create a new class that inherits from AbstractUser.
Then add any extra fields you want inside that class.
Examples
This example adds a birth date field to the user.
Django
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birth_date = models.DateField(null=True, blank=True)
This example adds a bio field that can be empty.
Django
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): bio = models.TextField(blank=True)
Don't forget to set AUTH_USER_MODEL to your custom user model in settings.
Django
# settings.py AUTH_USER_MODEL = 'accounts.CustomUser'
Sample Program
This code defines a custom user with a phone number field. Then it creates a user and prints the username and phone number.
Django
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): phone_number = models.CharField(max_length=15, blank=True, null=True) # Usage example (in Django shell or views): # Create a new user with phone number new_user = CustomUser.objects.create_user(username='alice', password='password123', phone_number='+123456789') print(f"Username: {new_user.username}") print(f"Phone: {new_user.phone_number}")
OutputSuccess
Important Notes
Changing AUTH_USER_MODEL after migrations is hard; set it before your first migration.
Time complexity is not affected by adding fields; it's about database queries.
Common mistake: forgetting to update AUTH_USER_MODEL in settings.py.
Summary
Custom user models let you add fields or change user behavior.
AbstractUser is a good base to keep Django's default features.
Always set AUTH_USER_MODEL before creating migrations.