← Back to Chapters

Decorators like @login_required

? Decorators like @login_required

? Quick Overview

Django provides several built-in decorators that allow you to control access to views in a convenient and secure manner. One of the most commonly used decorators is @login_required, which restricts access to a view so that only authenticated users can access it.

? Key Concepts

  • Decorators modify view behavior without changing view code
  • @login_required ensures only authenticated users can access a view
  • Unauthorized users are redirected to the login page
  • Decorators also work with class-based views

? Syntax / Theory

A decorator in Python is a function that wraps another function to extend its behavior. Django uses decorators to handle authentication, authorization, and permissions efficiently.

? Code Examples

? View Code Example
// Restrict access to authenticated users only
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def profile_view(request):
    return render(request, 'profile.html')
? View Code Example
// Configure custom login redirect URL
LOGIN_URL = '/accounts/login/'
? View Code Example
// Apply login_required to class-based view
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

@method_decorator(login_required, name='dispatch')
class ProfileView(TemplateView):
    template_name = 'profile.html'
? View Code Example
// Restrict view based on specific permissions
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render

@permission_required('auth.view_user', raise_exception=True)
def user_details_view(request):
    return render(request, 'user_details.html')

? Live Output / Explanation

Authenticated users can access protected views normally. Unauthenticated users are redirected to the login page. Permission-based decorators raise errors or block access if requirements are not met.

? Interactive / Visual Understanding

?
 
Protected View
Waiting for request...

Think of decorators as a security gate placed before your view logic. Requests pass through authentication checks before reaching the view.

? Use Cases

  • User dashboards and profiles
  • Admin-only or staff-only pages
  • Permission-based reports
  • Secure CRUD operations

✅ Tips & Best Practices

  • Always protect sensitive views using @login_required
  • Use permission decorators for fine-grained access control
  • Keep authentication logic out of views using decorators

? Try It Yourself

  • Protect a dashboard view using @login_required
  • Apply authentication to a class-based view
  • Create a permission-based view using @permission_required