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:
-
LoginRequiredMixinis 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_urlor modifyingLOGIN_URLin settings.
- Category Authentication & Authorization
- Total Views 656
- Last Modified 13 September, 2025
- Tags #cbv #mixin #authentication #login
Previous snippet
Restrict Access with @login_required (FBV)
Next snippet