UdaanPath Logo UdaanPath

📖 Chapters

Django & DRF Mastery: Build Robust Web Apps & APIs from Scratch

Django & DRF Mastery: Build Robust Web Apps & APIs from Scratch

Category: IT Fundamentals & Programming

Ever wanted to build powerful, modern web applications and robust APIs that power today's most dynamic online services? This is your ultimate guide! Welcome to Django & DRF Mastery, a comprehensive skill development course designed specifically for aspiring developers like …

User Management: Django's Built-in Authentication and Authorization

User Management: Django's Built-in Authentication and Authorization

Securely handling user logins, permissions, and what everyone can (or cannot) do on your site.

Who Are You? What Can You Do? The Pillars of Web Security

Almost every real-world web application needs to manage users. Whether it's a social network, an e-commerce store, or a blog with multiple authors, you need to know:

  • Who is visiting my site? (Are they a returning user, or a new guest?)
  • Are they who they claim to be? (Is that really Alice logging in, or someone else?)
  • What are they allowed to do? (Can Alice publish a post? Can Bob delete a comment?)

Building a secure and robust user management system from scratch is incredibly complex and prone to security vulnerabilities (think password hashing, session management, protecting against common attacks). Fortunately, Django comes with a battle-tested, built-in system for Authentication and Authorization that handles most of this heavy lifting for you.

At UdaanPath.com, we empower you to build secure applications by leveraging Django's robust features. This module will show you how to quickly implement user logins, protect sensitive views, and control user permissions, all with minimal code.

Core Concepts: Authentication vs. Authorization

These two terms are often confused but are distinct:

  • Authentication: "Who are you?" (Login)

    This is the process of verifying a user's identity. When you log in with a username and password, you are authenticating yourself. Django's authentication system manages users, hashed passwords, sessions (keeping you logged in), and provides views for login/logout.

  • Authorization: "What are you allowed to do?" (Permissions)

    Once a user is authenticated, authorization determines what resources or actions they are permitted to access. This involves checking if a user has specific permissions (e.g., 'can edit post', 'can delete comment') or belongs to certain groups that grant those permissions.

Django's Built-in User Model

Django provides a robust `User` model (`django.contrib.auth.models.User`) out of the box. It includes essential fields like username, email, password (hashed for security!), first name, last name, and flags like `is_active`, `is_staff`, `is_superuser`.

For most applications, you'll want to add custom fields to a user's profile (like a `bio`, `profile_picture`, or `phone_number`). The recommended way to do this for beginners is to create a separate model (e.g., `UserProfile`) and link it to Django's built-in `User` model using a `OneToOneField`.


# blog/models.py (Revisiting UserProfile if you created it in a previous module)
from django.db import models
from django.contrib.auth.models import User # Import Django's built-in User model

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE) # Link to Django's User
    bio = models.TextField(blank=True, null=True)
    profile_picture = models.ImageField(upload_to='profile_pics/', blank=True, null=True)
    # Add any other custom fields you need

    def __str__(self):
        return self.user.username

# Important: If you create this model, remember to:
# 1. python manage.py makemigrations
# 2. python manage.py migrate
# 3. You can register it in admin.py to manage via admin interface
            

Now, `request.user.userprofile` can be used to access custom user data, while `request.user.username`, `request.user.email` access the built-in fields.

Authentication in Action: Login, Logout, and Protecting Views

1. Setting up Auth URLs in `mysite/urls.py`

Django provides a set of authentication views that you can easily include.


# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    path('accounts/', include('django.contrib.auth.urls')), # Includes login, logout, password change/reset
    # Add a custom path for a success page after login/logout, if needed
    path('accounts/profile/', include('blog.urls')), # Example: redirect to blog's home after login
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
            

By including `django.contrib.auth.urls`, you automatically get URLs like `/accounts/login/`, `/accounts/logout/`, `/accounts/password_change/`, etc.

2. Configuring Login/Logout Redirects in `settings.py`

Tell Django where to redirect users after logging in or out.


# mysite/settings.py
# ...
LOGIN_REDIRECT_URL = '/blog/posts/' # Where to go after successful login (using a URL path)
LOGOUT_REDIRECT_URL = '/blog/posts/' # Where to go after successful logout
# You can also use named URLs:
# LOGIN_REDIRECT_URL = 'blog:post_list' # Assuming 'post_list' is a named URL in blog/urls.py
# LOGOUT_REDIRECT_URL = 'blog:post_list'
            

3. Creating Authentication Templates

Django's auth views look for templates in specific locations by default. Create a `registration` folder inside your `blog/templates` directory (i.e., `blog/templates/registration/`).

`blog/templates/registration/login.html` (for the login page):


<!-- blog/templates/registration/login.html -->
{% extends "blog/base.html" %}

{% block title %}Log In{% endblock %}

{% block content %}
<h2>Log In</h2>
<form method="post" action="{% url 'login' %}">
    {% csrf_token %}
    {{ form.as_p }} <!-- Render login form fields -->
    <button type="submit">Log In</button>
</form>
<p>Don't have an account? <a href="{% url 'admin:auth_user_add' %}">Sign Up (Admin demo)</a></p>
<!-- For a real user signup, you'd create a custom form and view -->
{% endblock %}
            

`blog/templates/registration/logged_out.html` (for the logout success page):


<!-- blog/templates/registration/logged_out.html -->
{% extends "blog/base.html" %}

{% block title %}Logged Out{% endblock %}

{% block content %}
<h2>You have been logged out.</h2>
<p><a href="{% url 'login' %}">Log in again</a></p>
{% endblock %}
            

4. Protecting Views with `@login_required`

To ensure a user must be logged in to access a view, use the `@login_required` decorator.


# blog/views.py (updated)
from django.shortcuts import render
from django.contrib.auth.decorators import login_required # Import the decorator
from django.contrib.auth.models import User # Or from .models import UserProfile if you need custom data

@login_required # This decorator redirects unauthenticated users to LOGIN_URL
def user_profile_view(request):
    # 'request.user' is automatically available and refers to the currently logged-in User instance
    # You can access related UserProfile data:
    try:
        user_profile = request.user.userprofile
    except UserProfile.DoesNotExist:
        user_profile = None # Handle case where user might not have a profile yet
    
    context = {
        'user': request.user,
        'user_profile': user_profile,
    }
    return render(request, 'blog/profile.html', context)
            

Now, create `blog/templates/blog/profile.html` to display this information.

Authorization in Action: Permissions and Groups

Django's authorization system uses permissions (e.g., 'can add post') and groups (collections of permissions) to control what authenticated users can do.

1. Permissions in the Admin

Django automatically creates default permissions for each model (`add_model`, `change_model`, `delete_model`, `view_model`). You can assign these to individual users or to groups in the Django Admin.
Go to `http://127.0.0.1:8000/admin/`, then "Users" or "Groups" to assign permissions.

2. Protecting Views with `@permission_required`

Similar to `login_required`, this decorator checks for specific permissions.


# blog/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import permission_required # Import this

@permission_required('blog.add_post', login_url='/accounts/login/', raise_exception=True)
def create_post_view(request):
    # This view will only be accessible to users who are logged in AND have the 'blog.add_post' permission.
    # If not logged in, it redirects to login_url. If logged in but no permission, it raises 403 error.
    return render(request, 'blog/create_post.html')
            

The permission string is `app_label.permission_codename`.

3. Checking Permissions in Templates (`{% if perms %}`)

You can dynamically show or hide content in your templates based on user permissions.


<!-- blog/templates/blog/base.html (or any other template) -->
<nav>
    <a href="/blog/posts/">Blog</a>
    {% if user.is_authenticated %}
        <span>Hello, {{ user.username }}!</span>
        <a href="{% url 'logout' %}">Logout</a>
        
        {% if user.is_staff %} <!-- Quick check for staff users (admin access) -->
            <a href="{% url 'admin:index' %}">Admin Dashboard</a>
        {% endif %}

        {% if perms.blog.add_post %} <!-- Check for specific permission -->
            <a href="{% url 'create_post' %}">Create New Post</a>
        {% endif %}

    {% else %}
        <a href="{% url 'login' %}">Login</a>
    {% endif %}
</nav>
            

Key Takeaways & Best Practices

  • Always use Django's built-in authentication and authorization system; don't try to build your own. It's secure and robust.
  • Understand the difference between Authentication ("Who are you?") and Authorization ("What can you do?").
  • Extend Django's `User` model with a `UserProfile` model (OneToOneField) for adding custom user data.
  • Include `django.contrib.auth.urls` for easy access to login/logout/password management views.
  • Use LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL in settings.py to control redirects.
  • Protect views requiring a login with the `@login_required` decorator.
  • Control access to views based on permissions using the `@permission_required` decorator.
  • Use {% if user.is_authenticated %} and {% if perms.app_label.permission_codename %} in templates for dynamic content display.
  • Security Note: Django handles password hashing automatically, which is a significant security feature.

Mini-Challenge: Build a Basic User Dashboard!

  1. Create a new view function in `blog/views.py` named `dashboard_view`.
  2. Protect `dashboard_view` using the `@login_required` decorator.
  3. Create a simple template (`blog/templates/blog/dashboard.html`) for this view. Inside it:
    • Display "Welcome, {{ user.username }}!"
    • If the user has a `UserProfile` model, display their `bio` or `profile_picture`.
    • Include a "Logout" link that uses `{% url 'logout' %}`.
  4. Add a URL pattern for `dashboard_view` in `blog/urls.py` (e.g., `path('dashboard/', views.dashboard_view, name='dashboard')`).
  5. Add a link to this "Dashboard" in your `base.html` that *only* appears if `user.is_authenticated`.
  6. Test: Log in (using `http://127.0.0.1:8000/accounts/login/`), then try to access your dashboard. Also, try accessing it when logged out (it should redirect you to the login page).

Module Summary: Your App is Now Secure and Personalized!

Fantastic work! In this module of your UdaanPath.com journey, you've gained mastery over Django's built-in Authentication and Authorization systems. You now can confidently manage user logins, protect your views, and control user access based on permissions. This is a monumental step towards building real-world, secure web applications.

Next up, we'll dive into an even more powerful way to write your views: Class-Based Views (CBVs), which offer a more structured and reusable way to build your application's logic.

ECHO Education Point  📚🎒

ECHO Education Point 📚🎒

ECHO Education Point proudly presents its Full Stack Development program 💻 – designed to launch your career in tech!

  • 🚀 Master both Front-End and Back-End technologies
  • 🧪 Includes 11 Mock Tests, 35 Mini Projects & 3 Website Builds
  • 🎯 Special training for job interviews & placement preparation

📍 Location: D-Mart Road, Meghdoot Nagar, Mandsaur
📞 Contact: 8269399715

Start your coding journey with expert instructor Vijay Jain (B.C.A., M.Sc., M.C.A.)
10 Days Free Demo Classes – Limited seats available!

#ECHO #FullStackDevelopment #MandsaurCoding