← Back to Chapters

Using Django’s Built-in User Model

? Using Django’s Built-in User Model

? Quick Overview

Django provides a powerful built-in User model for handling authentication, authorization, and user management. It includes fields like username, email, password, and helpful methods for login and permissions.

? Key Concepts

  • Authentication & authorization
  • User creation & retrieval
  • Superuser management
  • Custom user models

? Syntax / Theory

The built-in User model lives inside django.contrib.auth and works out-of-the-box when the auth app is enabled.

? Code Examples

? View Code Example
# Import Django's built-in User model
from django.contrib.auth.models import User

# Create a new user
user = User.objects.create_user('john_doe','john@example.com','password123')

# Fetch user by username
user = User.objects.get(username='john_doe')

# Access user fields
print(user.username)
print(user.email)
? View Code Example
# Authenticate and login a user
from django.contrib.auth import authenticate, login

user = authenticate(request,username='john_doe',password='password123')

if user is not None:
    login(request,user)
else:
    print("Invalid credentials")
? View Code Example
# Command to create Django superuser
python manage.py createsuperuser
? View Code Example
# Custom user model extending AbstractUser
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    birth_date = models.DateField(null=True,blank=True)

? Live Output / Explanation

Once authenticated, users gain access to protected views. Superusers can manage users through Django Admin.

? Interactive Concept

Think of Django’s authentication system as a plug-and-play module where the User model is the core identity object.

? Simulate: create_user()

Enter details below to see how Django creates a User object instance.

 
 

? Use Cases

  • Login & registration systems
  • Admin dashboards
  • Role-based access control

✅ Tips & Best Practices

  • Use the default User model unless customization is required
  • Decide on custom user models before initial migration
  • Secure passwords using Django’s hashing system

? Try It Yourself

  • Create users via Django shell
  • Login users using views
  • Extend user profile with custom fields