0
0
Djangoframework~3 mins

Why Custom user model with AbstractUser in Django? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could build user accounts that fit your app perfectly without breaking anything?

The Scenario

Imagine building a website where users need to log in, but the default user setup doesn't fit your needs. You want to add extra details like phone number or profile picture.

Without a custom user model, you try to patch things together manually, changing the default user everywhere.

The Problem

Manually changing the default user model is tricky and risky. It can break login, registration, and admin features. You might forget places to update, causing bugs and security holes.

It's like trying to fix a car engine while driving -- complicated and error-prone.

The Solution

Using a custom user model by extending AbstractUser lets you add fields and change behavior safely. Django handles the hard parts, so your new user model works smoothly everywhere.

This keeps your code clean and secure, and makes future changes easier.

Before vs After
Before
from django.contrib.auth.models import User
User.phone_number = ''  # Trying to add field manually
After
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
    phone_number = models.CharField(max_length=15, blank=True)
What It Enables

You can create user accounts tailored exactly to your app's needs, with extra info and custom behavior, all integrated seamlessly.

Real Life Example

A social media app where users have profile pictures, bios, and phone numbers stored directly on their user accounts, making login and profile management simple.

Key Takeaways

Default user model is limited and hard to change safely.

Extending AbstractUser lets you add custom fields and logic easily.

Custom user models keep your app secure, flexible, and maintainable.