New

Experience Smart HR with Horilla Mobile App

Google Play Store
Home / Blogs

How to Build a Custom User Model in Django? [2023]

Django
·

August 11, 2023

how-to-build-a-custom-user-model-in-django

Django, a powerful Python web framework, comes with a default user model that provides basic authentication and authorization features. However, in some cases, you may need to extend the default user model or create a custom user model from scratch to meet your project’s specific requirements.

To read more about implementing user authentication & authorization in Django, refer to our blog How to Implement User Authentication & Authorization in DjangoTo read more about the importance of Django model methods, refer to our blog An Overview of Django Model Methods in 2023

In this blog, we will explore how to build a custom user model in Django and integrate it into your application.

Prerequisites:

Before proceeding with this guide, it’s essential to possess a fundamental Knowledge of Python and Django. Additionally, ensure that Django is properly installed on your computer.

Step 1: Project Setup

Create a new Django project using the following command:

$ django-admin startproject customusermodel

Change into the project directory:

$ cd customusermodel

Step 2: App Creation

Create a new Django app to hold the custom user model using the following command:

python manage.py startapp accounts

Add the newly created app ‘accounts’ to the INSTALLED_APPS setting in the settings.py file of your project.

Step 3: Custom User Model Definition

Inside the ‘accounts’ app, open the models.py file and define your custom user model. Let’s create a model named ‘CustomUser’ that extends the AbstractBaseUser and PermissionsMixin classes provided by Django.

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set.')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        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)

        return self.create_user(email, password, **extra_fields)


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    def __str__(self):
        return self.email

The CustomUserManager class defines the methods for creating a regular user and a superuser. The CustomUser class defines the fields for the custom user model and sets the email field as the USERNAME_FIELD for authentication.

Step 4: Update Authentication Backend

To use the custom user model for authentication, update the AUTH_USER_MODEL setting in settings.py:

AUTH_USER_MODEL = 'accounts.CustomUser'

Step 5: Database Migration

Apply the database migrations to create the necessary tables for the custom user model:

$ python manage.py makemigrations
$ python manage.py migrate

Step 6: Integration and Usage

You can now use the custom user model in your Django application. Update any references to the default User model with the custom user model, ‘CustomUser’. For example, if you were using the default User model in a foreign key relationship, change it to the custom user model:

from django.contrib.auth import get_user_model

class SomeModel(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    # ...

Step 7: User Registration and Authentication

With the custom user model in place, you can register new users and authenticate them using Django’s built-in authentication views and forms. You can also create your own registration and authentication views if desired.

To read more about the importance of Django model methods, refer to our blog An Overview of Django Model Methods in 2023

Conclusion:

In this tutorial, we have explored how to build a custom user model in Django. By extending the AbstractBaseUser and PermissionsMixin classes, you can create a user model that meets your project’s specific requirements. Integrating the custom user model into your Django application allows you to leverage Django’s authentication and authorization features while providing a customized user experience.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.