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.
@login_required ensures only authenticated users can access a viewA decorator in Python is a function that wraps another function to extend its behavior. Django uses decorators to handle authentication, authorization, and permissions efficiently.
// 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')
// Configure custom login redirect URL
LOGIN_URL = '/accounts/login/'
// 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'
// 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')
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.
Think of decorators as a security gate placed before your view logic. Requests pass through authentication checks before reaching the view.
@login_required@login_required@permission_required