Django user model

Prerequisites

Intro

  • The Django User Model is a fundamental component of Django's authentication system
  • It serves as the backbone for user management, handling everything from account creation to authentication and permissions.
  • Whether we're building a small blog or a large-scale application, a solid understanding of the Django User Model is essential.

Django User Model

  • The Django User Model is a built-in model provided by Django as part of its django.contrib.auth module.
  • It represents users in our Django application and includes essential fields like username, password, email, and date_joined, etc.
  • This model is at the core of Django's authentication system, enabling features like login, logout, password management, and user permissions.

Key Features of the Django User Model

  • Authentication: The User Model works seamlessly with Django's authentication system, allowing we to verify user credentials and manage user sessions.
  • Permissions: It includes a permissions system that lets we control user access to different parts of our application.
  • Groups: Users can be organized into groups, which can have specific permissions, simplifying user management.
  • Customizability: While the default User Model is robust, Django allows we to extend or replace it to fit our application's unique needs.

Fields in the Default User Model

The default Django User Model includes the following fields:

  • username: A unique identifier for the user.
  • password: A hashed password for secure authentication.
  • email: An optional email field.
  • first_name and last_name: Optional fields for the user's first and last names.
  • is_staff: A boolean flag indicating whether the user can access the Django admin site.
  • is_active: A boolean flag indicating whether the user account is active.
  • is_superuser: A boolean flag indicating whether the user has all permissions.
  • last_login: The date and time of the user's last login.
  • date_joined: The date and time when the user account was created.
  • AUTH_USER_MODEL: Specifies the custom User Model to be used in the application.
  • LOGIN_URL: Defines the URL to redirect users to if they try to access a view that requires.
  • LOGIN_REDIRECT_URL: Specifies the URL to redirect users to after they successfully log in.
  • LOGOUT_REDIRECT_URL: Specifies the URL to redirect users to after they log out.

settings.py

...
AUTH_USER_MODEL = 'auth.User'
LOGIN_URL = '/user/login/'
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/'
...

Customizing the User Model

  • While the default User Model is sufficient for many applications, there are cases where we might need to customize it.
  • Django provides two main approaches:

    1. extending the User Model
    2. replacing the User Model.

Extending the User Model

  • One common way to extend the User Model is by creating a one-to-one relationship with a custom model.
  • This approach allows we to add additional fields without modifying the built-in User Model.
from django.contrib.auth.models import User
from django.db import models

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birth_date = models.DateField(null=True, blank=True)
    bio = models.TextField(max_length=500, blank=True)

    class Meta:
        db_table = "user_profile"

Replacing the User Model

  • For more extensive customizations, we can create a custom User Model by subclassing AbstractBaseUser and PermissionsMixin

my_app/models.py

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_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    objects = CustomUserManager()

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

    def __str__(self):
        return self.email

After defining the custom model, we must update setting AUTH_USER_MODEL in settings.py

my_project/settings.py

...
AUTH_USER_MODEL = 'my_app.CustomUser'
...

Working with Django User Model

Create User Object

  • We can create a new user using the create_user method provided by model manager UserManager or CustomUserManager if we customise the user model
from django.contrib.auth import get_user_model

User = get_user_model()

user = User.objects.create_user(
    username='johndoe',
    password='secret',
    email='[email protected]'
)
  • This method automatically handles password hashing, ensuring that user credentials are stored securely.

Authenticating a User

  • To authenticate a user, Django provides the authenticate function
from django.contrib.auth import authenticate

user = authenticate(username='johndoe', password='securepassword')
if user is not None:
    # User is authenticated
    print("User authenticated successfully")
else:
    # Authentication failed
    print("Authentication failed")

References: