Welcome back to CodeYourCraft! Today, we're going to learn how to extend the built-in User Model in Django to create a custom Profile model. This will allow us to store additional user-related data, making our applications more versatile and practical.
Let's get started!
In Django, the User Model represents the authentication framework's primary user entity. It comes with some predefined fields like username, email, first name, last name, password, and is_active, among others.
๐ก Pro Tip: Django's User Model is an extension of AbstractBaseUser and PermissionsMixin classes, providing built-in authentication functionality.
To create a custom Profile model, we'll follow these steps:
First, create a new Django app using the following command:
python manage.py startapp profilesNow, navigate to the profiles app and create a new model called CustomUser (remember to import necessary Django classes and modules):
# profiles/models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class CustomUserManager(BaseUserManager):
pass
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_active = models.BooleanField(_('active'), default=True)
is_staff = models.BooleanField(_('staff status'), default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']๐ Note: We've created a CustomUserManager class with no custom methods for now. Later, we can add any custom methods when needed.
Next, we need to register our CustomUser model with Django's authentication system:
profiles app's admin.py file, register our CustomUser model:# profiles/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
class CustomUserAdmin(BaseUserAdmin):
# List of fields displayed in the user's detail view
list_display = ('email', 'first_name', 'last_name', 'is_active', 'is_staff', 'date_joined')
# Fields that are searchable
search_fields = ('email', 'first_name', 'last_name')
# Fields that can be edited in the admin interface
list_filter = ('is_active', 'is_staff')
admin.site.unregistered_model(CustomUser)
admin.site.register(CustomUser, CustomUserAdmin)Finally, let's customize the user creation and login process:
settings.py, replace the default AUTH_USER_MODEL setting with our CustomUser:# settings.py
AUTH_USER_MODEL = 'profiles.CustomUser'urls.py, import the new CustomUser model and include the app's URL patterns:# urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from profiles.models import CustomUser
from profiles.forms import CustomAuthenticationForm
# ...
app_name = 'profiles'
urlpatterns = [
# ...
path('accounts/login/', auth_views.LoginView.as_view(template_name='profiles/login.html', authentication_form=CustomAuthenticationForm), name='login'),
path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
]CustomAuthenticationForm form in a new file called forms.py within the profiles app:# profiles/forms.py
from django import forms
from django.contrib.auth import authenticate, get_user_model
class CustomAuthenticationForm(forms.AuthenticationForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={'autofocus': True}))
def clean_email(self):
email = self.cleaned_data['email']
if CustomUser.objects.filter(email=email).exists():
return email
raise forms.ValidationError('The email is not registered.')
def get_user(self):
email = self.cleaned_data['email']
return get_user_model().objects.get(email=email)Now, you've learned how to extend Django's built-in User Model by creating a CustomUser model and customizing the user creation and login process. This will allow you to store additional user-related data in real-world projects.
๐ฏ Quiz Time!
What is the name of the custom User Model we created in this tutorial?