Django provides a class-based mixin called LoginRequiredMixin that restricts access to views so that only authenticated users can access them. It is commonly used with class-based views (CBVs) for clean and reusable authentication control.
@login_required decoratorThe LoginRequiredMixin is inherited before the CBV base class. Django checks authentication before processing the request.
# Import LoginRequiredMixin for authentication enforcement
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
# Profile view accessible only to authenticated users
class ProfileView(LoginRequiredMixin, TemplateView):
template_name = 'profile.html'
Authenticated users can view the profile page. Unauthenticated users are automatically redirected to the login page defined in settings.py.
Toggle the login status and try to visit the protected ProfileView.
# Custom login URL for this specific view
class CustomProfileView(LoginRequiredMixin, TemplateView):
template_name = 'profile.html'
login_url = '/custom-login/'
# Combining authentication and permission checks
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.views.generic import TemplateView
class AdminProfileView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
template_name = 'admin_profile.html'
permission_required = 'auth.view_user'
LoginRequiredMixin before CBV base classesLOGIN_URL for global controlLoginRequiredMixin to an existing CBV