Django User Model Tutorial
Introduction
The user model in Django is at the core of the authentication system. It stores the user data and manages user authentication. This tutorial will guide you through the essential aspects of Django's user model from scratch with detailed explanations and examples.
Creating a Custom User Model
By default, Django comes with a built-in user model, but it's a common practice to create a custom user model to extend its functionalities. To create a custom user model, follow these steps:
First, create a new Django app:
In the accounts/models.py
file, define the custom user model:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager 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 User(AbstractBaseUser): 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) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email
Updating Settings
Next, you need to update your settings to use the custom user model. Open the settings.py
file and add the following line:
Creating and Applying Migrations
After defining the custom user model, create and apply migrations to update the database schema.
Run the following commands:
python manage.py makemigrations
python manage.py migrate
Creating a Superuser
To create a superuser for your application, run the following command:
Follow the prompts to enter the superuser details.
Using the User Model
Now that you have set up the custom user model, you can use it in your views and forms. Here is an example of how to create a user programmatically:
from accounts.models import User user = User.objects.create_user( email='user@example.com', password='password123', first_name='John', last_name='Doe' )
You can also authenticate users using the custom user model:
from django.contrib.auth import authenticate user = authenticate(email='user@example.com', password='password123') if user is not None: # User is authenticated pass else: # Authentication failed pass
Conclusion
In this tutorial, we covered the basics of Django's user model, including how to create a custom user model, update settings, apply migrations, create a superuser, and use the custom user model in your application. By following these steps, you can extend and customize the user model to fit the needs of your Django project.