Creating Custom User Models in Django

 Django comes with a built-in authentication system that uses a User model to manage user accounts. While the default User model works for many applications, there are times when you may want to customize the model to suit your specific needs. In this tutorial, we'll show you how to create a custom user model in Django.


Why Create a Custom User Model?


There are several reasons why you might want to create a custom user model in Django:


Additional Fields: The default User model in Django only includes a few basic fields, such as username, email, and password. If you need to store additional information about your users, such as their full name or address, you'll need to create a custom user model.


Unique Identifiers: By default, Django uses the username field as the unique identifier for users. However, you may want to use a different field, such as email or a custom ID, as the unique identifier.


Integration with Third-Party Authentication: If you're using a third-party authentication system, such as OAuth or LDAP, you may need to create a custom user model to integrate with that system.


Step 1: Create a New Django Project


To get started, create a new Django project using the following command:


bash


django-admin startproject myproject

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


bash


python manage.py startapp users

Step 2: Create a Custom User Model


In the users/models.py file, define a new model that inherits from AbstractBaseUser and PermissionsMixin. The AbstractBaseUser class provides the basic functionality for a user model, while the PermissionsMixin class adds the necessary fields for handling permissions and groups.


python


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

from django.db import models


class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(unique=True)

    first_name = models.CharField(max_length=30)

    last_name = models.CharField(max_length=30)

    is_staff = models.BooleanField(default=False)

    is_active = models.BooleanField(default=True)


    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['first_name', 'last_name']


    objects = UserManager()


    def __str__(self):

        return self.email

In this example, we've added three fields to the model: email, first_name, and last_name. We've also set the USERNAME_FIELD attribute to email to use the email address as the unique identifier for users. Finally, we've defined a custom manager for the model by creating a UserManager class.


Step 3: Create a Custom User Manager


In the users/managers.py file, create a custom manager for the User model. This manager will be responsible for creating and manipulating user objects.


python


from django.contrib.auth.models import BaseUserManager


class UserManager(BaseUserManager):

    def create_user(self, email, first_name, last_name, password=None):

        if not email:

            raise ValueError('Users must have an email address')


        user = self.model(

            email=self.normalize_email(email),

            first_name=first_name,

            last_name=last_name,

        )


        user.set_password(password)

        user.save(using=self._db)


        return user


    def create_superuser(self, email, first_name, last_name, password):

        user = self.create_user(

            email=self.normalize_email(email),

            first_name=first_name,

            last_name=last_name,

            password=password,

        )


        user.is_staff = True

        user.is_superuser = True

        user.save(using=self._db)


        return user


In this example, we've defined two methods: create_user() and create_superuser(). The create_user() method creates a new user object, while the create_superuser() method creates a new user object with additional staff and superuser permissions.


Step 4: Update the Settings File


In the myproject/settings.py file, update the AUTH_USER_MODEL setting to use the new custom user model:


python


AUTH_USER_MODEL = 'users.User'

This tells Django to use the User model defined in the users app as the default user model for the project.


Step 5: Run Migrations


Finally, run the migrations to create the new user model:


bash


python manage.py makemigrations

python manage.py migrate

This will create a new database table for the custom user model.


Conclusion


In this tutorial, we've shown you how to create a custom user model in Django. By creating a custom user model, you can add additional fields to the user model, use a unique identifier other than the username, and integrate with third-party authentication systems. With these steps, you can easily create a custom user model that meets your application's specific needs.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...