Django’s Built-in User Model
Django, a powerful web framework, offers a built-in user authentication system that is both easy to implement and customize. At the core of this system lies Django’s User
model, a versatile component for handling user management tasks such as authentication, registration, and permissions.
Overview of Django's User
Model
The User
model is part of Django’s auth
application, which is included by default in new Django projects. This model is a class that extends AbstractUser
, which itself extends AbstractBaseUser
, providing a set of fields and methods to simplify the management of user accounts.
Key Fields in the User
Model
The User
model includes several predefined fields designed to cover common user management needs:
-
Username (
username
):-
Description: A string field that stores a unique identifier for each user. It is often used as a login credential.
-
Example:
user = User.objects.create_user(username='john_doe', password='securepassword123') print(user.username) # Output: john_doe
-
-
Password (
password
):-
Description: A field that stores the hashed password of the user. Django uses secure hashing algorithms like PBKDF2 by default.
-
Example:
user = User.objects.get(username='john_doe') user.set_password('new_securepassword456') user.save()
-
-
Email (
email
):-
Description: An optional field for storing the user’s email address. This can be set as mandatory and unique based on project requirements.
-
Example:
user = User.objects.create_user(username='jane_doe', email='jane@example.com', password='anotherpassword') print(user.email) # Output: jane@example.com
-
-
First Name (
first_name
) and Last Name (last_name
):-
Description: Fields for storing the user's first and last names, respectively.
-
Example:
user = User.objects.get(username='john_doe') user.first_name = 'John' user.last_name = 'Doe' user.save()
-
-
Date Joined (
date_joined
):-
Description: A timestamp indicating when the user account was created.
-
Example:
print(user.date_joined) # Output: 2024-08-29 12:34:56.789012
-
-
Last Login (
last_login
):-
Description: Tracks the last time the user successfully logged in.
-
Example:
print(user.last_login) # Output: 2024-08-29 14:20:33.123456
-
-
Is Active (
is_active
):-
Description: A Boolean field indicating if the user’s account is active. Inactive users cannot log in.
-
Example:
user.is_active = False user.save()
-
-
Is Staff (
is_staff
):-
Description: A Boolean field that determines if the user has access to the Django admin interface.
-
Example:
user.is_staff = True user.save()
-
-
Is Superuser (
is_superuser
):-
Description: Indicates whether the user has all permissions without explicitly assigning them.
-
Example:
user.is_superuser = True user.save()
-
Customizing the User
Model
Django’s built-in User
model is versatile, but sometimes you may need additional fields or different behavior. Here are two common ways to customize the user model:
-
Extending the
User
Model with a Profile Model:-
This approach involves creating a separate model, usually called a "Profile" model, with a one-to-one relationship with the
User
model. -
Example:
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField(null=True, blank=True) profile_picture = models.ImageField(upload_to='profile_pics/', null=True, blank=True) def __str__(self): return f'{self.user.username} Profile'
-
-
Substituting the
User
Model:-
For extensive customization, you can create a custom model that inherits from
AbstractUser
orAbstractBaseUser
, and specify it in yoursettings.py
. -
Example:
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): phone_number = models.CharField(max_length=15, unique=True, null=True, blank=True) def __str__(self): return self.username # In settings.py AUTH_USER_MODEL = 'myapp.CustomUser'
-
User Model Methods
The User
model provides several built-in methods that make working with user data straightforward:
-
check_password(raw_password)
:-
Description: Verifies if a provided password matches the user’s stored password.
-
Example:
user = User.objects.get(username='john_doe') print(user.check_password('securepassword123')) # Output: True
-
-
set_password(raw_password)
:-
Description: Hashes and sets a new password for the user.
-
Example:
user.set_password('new_password') user.save()
-
-
get_full_name()
:-
Description: Returns the user’s full name by combining the
first_name
andlast_name
fields. -
Example:
print(user.get_full_name()) # Output: John Doe
-
-
get_short_name()
:-
Description: Returns the user’s first name.
-
Example:
print(user.get_short_name()) # Output: John
-
-
has_perm(perm)
andhas_perms(perm_list)
:-
Description: Checks if the user has the specified permission(s).
-
Example:
print(user.has_perm('auth.change_user')) # Output: True or False
-
-
has_module_perms(app_label)
:-
Description: Checks if the user has any permissions within a specified app.
-
Example:
print(user.has_module_perms('auth')) # Output: True or False
-
Connecting the User
Model with Forms
The User
model is commonly used in forms to handle user registration and login. Django provides a UserCreationForm
and AuthenticationForm
that are tailored for these purposes.
-
Example of User Creation Form:
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] # In views.py from django.shortcuts import render, redirect from .forms import CustomUserCreationForm def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form})
-
Example of Using the Form in a Template:
<!-- register.html --> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form>
Conclusion
Django’s built-in User
model is a robust solution for managing user data in web applications. It comes equipped with essential fields and methods that handle common use cases, while also offering flexibility through extensions and customizations. By understanding and leveraging these features, you can build secure and efficient user management systems tailored to your application's needs.