Extending User Model (Profile) in Django Tutorial

beginner
14 min

Extending User Model (Profile) in Django Tutorial

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!

Understanding the User Model

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.

Creating a Custom Profile Model

To create a custom Profile model, we'll follow these steps:

  1. Create a new Django app (if not already done)
  2. Define the Profile model with additional fields
  3. Register our new Profile model with Django's authentication system
  4. Customize the user creation and login process

Step 1: Creating a New Django App

First, create a new Django app using the following command:

bash
python manage.py startapp profiles

Step 2: Defining the Profile Model

Now, navigate to the profiles app and create a new model called CustomUser (remember to import necessary Django classes and modules):

python
# 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.

Step 3: Registering the Custom User Model

Next, we need to register our CustomUser model with Django's authentication system:

  1. In the profiles app's admin.py file, register our CustomUser model:
python
# 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)

Step 4: Customizing User Creation and Login

Finally, let's customize the user creation and login process:

  1. In the project's settings.py, replace the default AUTH_USER_MODEL setting with our CustomUser:
python
# settings.py AUTH_USER_MODEL = 'profiles.CustomUser'
  1. In the project's urls.py, import the new CustomUser model and include the app's URL patterns:
python
# 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'), ]
  1. Create a custom CustomAuthenticationForm form in a new file called forms.py within the profiles app:
python
# 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)

Wrapping Up

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!

Quick Quiz
Question 1 of 1

What is the name of the custom User Model we created in this tutorial?