Django Custom User Model

Django Custom User Model

This blog post will discuss the need for a custom User model. We will build the User model from scratch, the steps involved in creating one in Django, and some best practices for managing a custom User model.

Why use a custom User model?

You might want to use a custom User model in Django for several reasons. Here are a few scenarios where a custom User model can be beneficial:

  1. Additional fields: The default User model comes with a set of pre-defined fields, but there may be situations where you need to store additional information about users. Creating a custom User model allows you to add fields that are specific to your application’s needs.

  2. Authentication via email or phone number: Django’s default User model uses the username field for authentication. However, if you prefer email addresses or phone numbers for authentication, you can create a custom User model with these fields as the primary identifier.

  3. Third-party authentication: If you want to support authentication through a third-party service such as Facebook or Google, you may need to create a custom User model that stores the user’s unique identifier for that service.

Creating a Custom User Model in Django

Creating a custom User model in Django involves several steps. Here is an overview of the process:

Step 1: Create a new Django app

To create a custom User model, you’ll need to create a new Django app that will contain the model definition. You can use the following command to create a new app:

python manage.py startapp users

Step 2: Define the custom User model

Once you have created the app, we will create the custom user model in the models.py file:

from django.db import models  
from django.contrib.auth.models import AbstractBaseUser

# Create your models here.  
class CustomUser(AbstractBaseUser):  
    username = None  
    email = models.EmailField('email_address', unique=True, max_length = 200)  
    date_joined = models.DateTimeField(default=timezone.now)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'  
    REQUIRED_FIELDS = [] 

    objects = CustomUserManager()

    def __str__(self):
        return self.username

In this example, we are inheriting Django’s AbstractUser class, which provides a set of basic fields for authentication. Then, we added a field for email, is_admin, is_active, is_staff, is_superuser, and date_joined. Note that the __str__ method has also been overridden to return the user’s username.

Step 3: Create the Model Manager

Django provides built-in methods for the user manager. But if we are creating the custom user model, we need to override the default methods. A UserManager is a class that provides a set of methods for creating, retrieving, updating, and deleting User objects in the database. By creating a custom UserManager, you can add methods to handle specific functionality related to your custom User model.

Here is an example of a custom UserManager that includes a method for creating superusers with an email address:

from django.contrib.auth.base_user import BaseUserManager  


class CustomUserManager(BaseUserManager): 

    def create_superuser(self, email, password, **extra_fields):  
        extra_fields.setdefault('is_staff', True)  
        extra_fields.setdefault('is_superuser', True)  
        extra_fields.setdefault('is_active', True)  
        extra_fields.setdefault('username', email)

        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)  

    def create_user(self, email, password, **extra_fields): 
        if not email:  
            raise ValueError('The Email must be set')  
        email = self.normalize_email(email)  

        user = self.model(email=email, **extra_fields)  
        user.set_password(password)  
        user.save()  
        return user

In this example, we have created a custom UserManager that inherits from Django’s BaseUserManager. We have added two methods, create_superuser and create_user, which allows us to create User objects with specific properties.

Step 4: Update the settings file

To use the custom User model in your project, you’ll need to update the AUTH_USER_MODEL setting in the project’s settings.py file. Open the settings.py file and register your custom user model:

AUTH _USER_MODEL = users.CustomUser

Step 5: Run migrations

After updating the AUTH_USER_MODEL setting, you’ll need to run migrations to update the database schema. You can use the following command to run migrations:

python manage.py makemigrations  
python manage.py migrate

Conclusion

Using a custom User model in Django can provide greater flexibility and control over the authentication and user management system in your application. By creating a custom User model, you can add additional fields, methods, and functionality to suit the specific needs of your project.

Creating a custom User model in Django involves several steps, including subclassing the AbstractBaseUser model, setting the AUTH_USER_MODEL setting in the settings file, and creating a custom user manager.

A custom user manager allows you to add additional methods for user creation, querying, and authentication and can be a powerful tool for extending the functionality of your custom User model.