How to Extend Django User Model using AbstractUser

Django, a powerful Python web framework, offers a built-in User model for authentication purposes. However, when your project demands additional user-specific information, extending the User model becomes essential. In this blog, we’ll explore how to extend Django User Model using the AbstractUser method, accompanied by a comprehensive example.

Understanding AbstractUser

The AbstractUser class in Django’s django.contrib.auth.models module provides a straightforward way to extend the User model. By subclassing AbstractUser, you can seamlessly add custom fields and functionalities while retaining the built-in authentication features.

Read More on Extending the Django User Model: Exploring Various Approaches

Benefits of Using AbstractUser

  • Simplicity: Subclassing AbstractUser is less complex than other methods, making it suitable for projects with moderate customization needs.
  • Built-in Features: You retain standard authentication features and can easily use Django’s admin site for user management.
  • Efficiency: AbstractUser handles common user-related functionalities, letting you focus on the additional fields your project requires.

Step-by-Step Implementation

Let’s dive into the process of extending Django User Model using the AbstractUser method, using a practical example of creating a CustomUser model.

Note: We have create a already created our django project using our blog on Django Basic Template Boilerplate Skeleton Project. For this example, we have created a app named “accounts“.

Step 1: Subclass AbstractUser

# accounts/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    bio = models.TextField(max_length=500, blank=True)
    profile_picture = models.ImageField(upload_to='profile_pics/', blank=True)

Step 2: Update Settings

In your project’s settings.py, specify your custom User model:

AUTH_USER_MODEL = 'your_app.CustomUser'

Step 3: Applying Migrations

Run the following commands to apply migrations and create the custom User model:

python manage.py makemigrations
python manage.py migrate

Conclusion

Extending Django User Model using the AbstractUser method offers an efficient way to enhance the User model with custom fields. The step-by-step example in this blog illustrates how to create a CustomUser model, making it easier to add attributes like user bios and profile pictures. By following this approach, you ensure your application is better equiped to handle diverse user-specific requirements. Remember that selecting the extension method depends on your project’s complexity and goals, and AbstractUser offers an accessible entry point for customization.

Find this project on Github.

Blogs You Might Like to Read!