Restrict Access with LoginRequiredMixin (CBV)

A snippet to protect Django class-based views using LoginRequiredMixin.


# views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView

class DashboardView(LoginRequiredMixin, TemplateView):
    template_name = 'dashboard.html'
  

# templates/dashboard.html

<h2>Welcome to your dashboard</h2>
<p>Only authenticated users can view this page.</p>
  
Explanation:
  • LoginRequiredMixin is used to restrict access to class-based views.
  • If the user is not authenticated, they will be redirected to the login page.
  • This mixin must be placed before the view class (e.g., TemplateView) in the inheritance order.
  • You can change the redirect URL by setting login_url or modifying LOGIN_URL in settings.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.