Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

User Management in Django

Introduction

User management is a critical aspect of web applications, ensuring that users can register, log in, and manage their profiles securely. In Django, user management is largely handled by the built-in authentication system, which provides a robust framework for managing users.

Setting Up User Authentication

To get started with user management, you need to ensure that the Django authentication system is properly set up. First, add the following apps to your INSTALLED_APPS in your settings.py file:

INSTALLED_APPS = [
    ...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    ...
]
                

Next, make sure your middleware includes the following:

MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
]
                

Creating a User Model

Django provides a default user model, but you may want to customize it by creating a custom user model. To do this, you need to create a new model that inherits from AbstractBaseUser and PermissionsMixin. Here is an 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)
        return self.create_user(email, password, **extra_fields)

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

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email
                

After defining your custom user model, update the AUTH_USER_MODEL setting in your settings.py:

AUTH_USER_MODEL = 'yourapp.CustomUser'
                

User Registration

User registration typically involves creating a registration form and view. Below is an example of how to create a registration form using Django forms:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('email', 'first_name', 'last_name')
                

Next, create a view for handling user registration:

from django.urls import reverse_lazy
from django.views import generic
from .forms import CustomUserCreationForm

class SignUpView(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
                

Finally, create a template signup.html to render the registration form:




    Sign Up


    

Sign Up

{% csrf_token %} {{ form.as_p }}