Custom User Model in Django


Introduction

Django allows you to use a custom user model, which is a powerful feature for projects that require more than the built-in User model. In this guide, we'll explore how to create and use a custom user model in Django.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Django: You should have Django installed. If not, use
    pip install django
    to install it.
  • Django Project: You should have a Django project set up. If not, refer to the guide on creating your first Django project.

Step 1: Create a New User Model

To create a custom user model, you need to define a new model that inherits from

AbstractBaseUser
and
PermissionsMixin
.


Sample Code

In your app's

models.py
file, create a custom user model. For example:

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)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have 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

Step 2: Update Authentication Settings

Configure your project to use the custom user model for authentication.


Sample Code

In your project's

settings.py
, specify the custom user model:

# settings.py
AUTH_USER_MODEL = 'yourapp.CustomUser'

Conclusion

Using a custom user model in Django provides greater flexibility and control over user authentication. By following these steps, you can define and use a custom user model tailored to your project's requirements.