Custom User Model

Back

Loading concept...

Django Authentication: Custom User Model 🏰

The Story of Building Your Own Identity System

Imagine you’re the mayor of a brand new city. Every city needs to keep track of its citizens, right? Django gives you a basic citizen registry (the default User model), but what if your city is special? What if you want to track things the default registry doesn’t have—like a citizen’s favorite ice cream flavor or their superhero name?

That’s where Custom User Models come in! You get to design your own registry from scratch.


🎭 The Three Heroes of Custom User Authentication

Think of these as three superheroes who work together:

  1. AbstractUser - The “Almost Ready” Hero 🦸
  2. Custom User Setup - The “Building Blueprint” Hero 🏗️
  3. User Registration - The “Welcome Wagon” Hero 🎉

Let’s meet each one!


1. AbstractUser Classes: The “Almost Ready” Hero 🦸

What is AbstractUser?

Think of AbstractUser like a pre-built house that’s almost complete. It has walls, a roof, windows, and doors. You just need to add your personal touches—paint color, furniture, maybe a swimming pool!

Simple Explanation:

  • Django says: “Here’s a user with username, email, password, first_name, last_name”
  • You say: “Great! But I also want to store their phone number!”
  • AbstractUser says: “No problem! Just add what you need on top of me!”

The Two Base Classes

Django gives you two options:

graph TD A["AbstractBaseUser"] -->|"Bare bones<br>Build everything"| B["Maximum Control"] C["AbstractUser"] -->|"Pre-built<br>Just add extras"| D["Quick &amp; Easy"] style A fill:#ff6b6b style C fill:#4ecdc4
Class What It’s Like When to Use
AbstractUser A furnished apartment You want Django’s fields + your own
AbstractBaseUser An empty plot of land You want to build EVERYTHING yourself

Real Code Example

Here’s how you use AbstractUser (the easy way):

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

class CustomUser(AbstractUser):
    # AbstractUser already has:
    # username, email, password,
    # first_name, last_name

    # Now add YOUR special fields:
    phone_number = models.CharField(
        max_length=15,
        blank=True
    )
    birth_date = models.DateField(
        null=True,
        blank=True
    )
    bio = models.TextField(
        max_length=500,
        blank=True
    )

What just happened?

  • You inherited ALL the user features Django already built
  • You added three NEW fields: phone, birthday, and bio
  • That’s it! Your custom user is ready!

2. Custom User Setup: The “Building Blueprint” Hero 🏗️

The Golden Rule ⚠️

START with a Custom User Model! Don’t use Django’s default User, then try to switch later. It’s like trying to change the foundation of a house after it’s built!

Step-by-Step Setup

Think of this like setting up a new video game character:

Step 1: Create the Model (Design your character)

# accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # Your custom fields here
    nickname = models.CharField(
        max_length=50,
        blank=True
    )

Step 2: Tell Django About It (Register your character)

# settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'

This one line is SUPER IMPORTANT! It tells Django: “Hey, use MY user model, not yours!”

Step 3: Create a Manager (optional but powerful)

# accounts/models.py
from django.contrib.auth.models import (
    AbstractUser,
    BaseUserManager
)

class CustomUserManager(BaseUserManager):
    def create_user(
        self, email, password=None, **extra
    ):
        if not email:
            raise ValueError('Email required!')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(
        self, email, password=None, **extra
    ):
        extra['is_staff'] = True
        extra['is_superuser'] = True
        return self.create_user(
            email, password, **extra
        )

Step 4: Make Migrations (Save your work)

python manage.py makemigrations
python manage.py migrate

The Setup Diagram

graph TD A["1. Create Model"] --> B["2. Update settings.py"] B --> C["3. Create Manager"] C --> D["4. Run Migrations"] D --> E["Ready to Use!"] style E fill:#4ecdc4

3. User Registration: The “Welcome Wagon” Hero 🎉

What is User Registration?

When a new person joins your website, they need to:

  1. Fill out a form (name, email, password)
  2. Click “Sign Up”
  3. Get a new account created

This is User Registration—welcoming new users to your app!

Creating a Registration Form

# accounts/forms.py
from django import forms
from django.contrib.auth.forms import (
    UserCreationForm
)
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = CustomUser
        fields = (
            'username',
            'email',
            'password1',
            'password2'
        )

What’s happening?

  • UserCreationForm handles password validation
  • We add email as required
  • Meta says which fields to show

Creating the Registration View

# accounts/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,
        'registration/register.html',
        {'form': form}
    )

The Registration Flow

graph TD A["User visits /register"] --> B["Empty form shown"] B --> C["User fills form"] C --> D{Form valid?} D -->|Yes| E["Save to database"] D -->|No| F["Show errors"] F --> C E --> G["Redirect to login"] style G fill:#4ecdc4

Simple Registration Template

<!-- templates/registration/register.html -->
<h1>Create Account</h1>

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">
        Sign Up
    </button>
</form>

🎯 Putting It All Together

Here’s how the three heroes work as a team:

graph TD A["AbstractUser"] -->|Provides base| B["CustomUser Model"] B -->|Configured in| C["settings.py"] C -->|Used by| D["Registration Form"] D -->|Creates| E["New User in Database"] style A fill:#ff6b6b style B fill:#feca57 style C fill:#54a0ff style D fill:#5f27cd style E fill:#4ecdc4

đź’ˇ Key Takeaways

Concept One-Line Summary
AbstractUser Pre-built user with extras you can add
Custom User Setup Set AUTH_USER_MODEL BEFORE first migration
User Registration Form + View + Template = New users!

🚀 Pro Tips

  1. Always start with a custom user - Even if you don’t need extra fields now, you might later!

  2. Use email as username - Many modern apps do this. It’s easier for users to remember.

  3. Never store plain passwords - Django’s set_password() hashes them automatically.

  4. Test registration flow - Create a test user before launching your app!


🎮 Real-World Example

Imagine building Instagram. You’d want:

class CustomUser(AbstractUser):
    # Instagram-like fields
    profile_picture = models.ImageField(
        upload_to='profiles/',
        blank=True
    )
    bio = models.CharField(
        max_length=150,
        blank=True
    )
    is_verified = models.BooleanField(
        default=False
    )
    followers_count = models.IntegerField(
        default=0
    )

The default Django User can’t do this. But with Custom User Model, you can build anything!


🎉 You Made It!

You now understand:

  • âś… Why we need custom user models
  • âś… How AbstractUser gives you a head start
  • âś… How to set up your custom user properly
  • âś… How to let new users register

Next step: Build something! Create your own custom user with a unique field that makes sense for your app. Happy coding! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.