← Back to Chapters

Using LoginRequiredMixin in CBVs

? Using LoginRequiredMixin in CBVs

? Quick Overview

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.

? Key Concepts

  • Restricts CBV access to logged-in users
  • Redirects unauthenticated users to login page
  • Cleaner alternative to @login_required decorator

? Syntax / Theory

The LoginRequiredMixin is inherited before the CBV base class. Django checks authentication before processing the request.

? Code Example

? View Code Example
# 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'

? Live Output / Explanation

Authenticated users can view the profile page. Unauthenticated users are automatically redirected to the login page defined in settings.py.

? Interactive Demo

Toggle the login status and try to visit the protected ProfileView.

Status: Guest
? example.com/
Ready to Test

Click "Visit /profile/" to send a request.

? Custom Redirect URL

? View Code Example
# Custom login URL for this specific view
class CustomProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'profile.html'
    login_url = '/custom-login/'

? Multiple Mixins

? View Code Example
# 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'

? Use Cases

  • User dashboards
  • Admin panels
  • Profile and account pages

✅ Tips & Best Practices

  • Always place LoginRequiredMixin before CBV base classes
  • Use LOGIN_URL for global control
  • Combine with permission mixins for fine-grained security

? Try It Yourself

  • Add LoginRequiredMixin to an existing CBV
  • Customize login redirect URL
  • Experiment with multiple permission-based mixins