Last modified: Dec 03, 2026
Django login_required with CBV
Django gives you two ways to build views. You can use function-based views or class-based views (CBVs). Both are powerful. But protecting them with authentication works a bit differently.
In this guide, you will learn how to use login_required with Django CBVs. We will cover the decorator, the LoginRequiredMixin, and the common mistakes beginners make.
By the end, you will know exactly which tool to pick for each situation. Let's start with the basics.
What Is login_required?
login_required is a decorator from django.contrib.auth.decorators. It checks if the current user is logged in. If not, it redirects them to the login page.
It works perfectly with function-based views. Here is a quick example:
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@login_required
def dashboard(request):
# Only logged-in users can reach this line
return HttpResponse("Welcome to your dashboard")
When an anonymous user visits this view, Django sends them to settings.LOGIN_URL. By default, that is /accounts/login/.
After login, the user is sent back to the original page. This happens through the next query parameter. The decorator adds it automatically.
Why login_required Fails on CBVs
A class-based view is a class, not a function. The decorator expects a function. So you cannot simply wrap the whole class like this:
# This does NOT work as expected
@login_required
class DashboardView(View):
pass
Django will raise a TypeError. The decorator tries to call the class like a function and fails.
You have two correct options. You can decorate the dispatch method. Or you can use a mixin. Let's look at both.
Option 1: Decorate the dispatch Method
Every CBV calls dispatch to route the request. If you protect dispatch, you protect the whole view. This is the cleanest way to reuse the decorator.
You can use method_decorator from django.utils.decorators. It converts a function decorator into a method decorator.
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
from django.http import HttpResponse
@method_decorator(login_required, name="dispatch")
class DashboardView(View):
def get(self, request):
# Anonymous users never reach this method
return HttpResponse("Welcome to your dashboard")
This approach is explicit. It keeps the decorator visible at the top of the class. It also works with any CBV, including TemplateView and DetailView.
You can even apply multiple decorators at once. Just pass them as a list:
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
@method_decorator(login_required, name="dispatch")
@method_decorator(permission_required("shop.view_orders", raise_exception=True), name="dispatch")
class OrdersView(TemplateView):
template_name = "orders.html"
Remember that decorators apply from the bottom up. The lowest decorator runs first. Keep that order in mind when you stack them.
Option 2: Use LoginRequiredMixin
Django ships with a ready-made mixin called LoginRequiredMixin. It lives in django.contrib.auth.mixins. It does the same job as the decorator, but in a Pythonic class style.
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = "dashboard.html"
login_url = "/accounts/login/" # Optional override
redirect_field_name = "next" # Default value
This mixin overrides dispatch for you. It checks the user and redirects anonymous visitors. It also supports two extra attributes: login_url and redirect_field_name.
If you want to understand how mixins fit into class design, read this guide on inheritance in Python explained. Mixins are just multiple inheritance in action.
Mixin Order Matters
Always put LoginRequiredMixin on the left side of the class definition. Python reads base classes from left to right. The mixin must come before the view class.
# Correct order
class DashboardView(LoginRequiredMixin, TemplateView):
pass
# Wrong order: the mixin's dispatch may never run
class DashboardView(TemplateView, LoginRequiredMixin):
pass
This rule comes straight from Python's method resolution order. If that sounds new, this article on types of Python inheritance explains the idea in plain terms.
Decorator vs Mixin: Which Should You Use?
Both options are safe. The choice depends on your style and your codebase.
Use the decorator when you want the protection to be visible. It reads well at the top of the class. It also works if you prefer function-style tools.
Use the mixin when you want to set login_url per view. It is also cleaner when you combine several auth rules, like login plus permissions.
Many teams pick one style and stick with it. Consistency makes code easier to review. It also helps new developers find auth rules quickly.
How the Redirect Works
When a guest hits a protected view, Django redirects them to the login URL. It adds the original path as a next parameter.
Here is what the browser sees:
GET /dashboard/ HTTP/1.1
Host: example.com
HTTP/1.1 302 Found
Location: /accounts/login/?next=/dashboard/
After the user logs in, the login view reads next and sends them back. This only works if your login template includes the hidden next field. Django's built-in login view handles this for you.
One warning: never trust the next value blindly. Django's login view validates it and blocks external URLs. If you write a custom login view, do the same check.
Protecting Class Methods with method_decorator
Sometimes you only want to protect one HTTP method. For example, a view might allow public reads but require login for writes. You can decorate a single method.
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
from django.http import HttpResponse
class ArticleView(View):
def get(self, request):
# Public: anyone can read
return HttpResponse("Public article")
@method_decorator(login_required)
def post(self, request):
# Private: only logged-in users can post
return HttpResponse("Article saved")
Note that name is not needed here. The decorator sits directly on the method, so Django knows what to wrap.
This pattern is useful for APIs and form views. It keeps public and private behavior in one class without extra files.
Common Mistakes to Avoid
Mistake 1: Decorating the class directly. This raises a TypeError. Use dispatch or a mixin instead.
Mistake 2: Wrong mixin order. If LoginRequiredMixin is not first, the check may be skipped. Always place it on the left.
Mistake 3: Forgetting the login URL. If LOGIN_URL is not set and the default path does not exist, users hit a 404. Set it in settings.
Mistake 4: Protecting only get. A user could still send a POST request. Protect dispatch unless you have a good reason not to.
Mistake 5: Confusing login with permission. Login checks identity. Permission checks rights. Use PermissionRequiredMixin for the second job.
If you are still getting comfortable with classes, this primer on Python class basics for beginners will make CBVs feel much less mysterious.
Testing Your Protected View
Always test both cases: anonymous and logged in. Django's test client makes this easy.
from django.test import TestCase
from django.urls import reverse
class DashboardTests(TestCase):
def test_anonymous_redirected(self):
response = self.client.get(reverse("dashboard"))
# Expect a redirect to the login page
self.assertEqual(response.status_code, 302)
self.assertIn("/accounts/login/", response.url)
def test_logged_in_allowed(self):
self.client.login(username="alice", password="secret123")
response = self.client.get(reverse("dashboard"))
self.assertEqual(response.status_code, 200)
Run the tests and you will see clear output:
$ python manage.py test
..
----------------------------------------------------------------------
Ran 2 tests in 0.412s
OK
These two tests catch most auth regressions. Add them for every protected view you build.
Bonus: Settings That Support login_required
Two settings make this feature smoother. Set LOGIN_URL to your real login path. Set LOGIN_REDIRECT_URL to where users land after login.
# settings.py
LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL = "/dashboard/"
LOGOUT_REDIRECT_URL = "/"
With these in place, the decorator and the mixin both work without extra configuration. Your redirects stay consistent across the whole project.
Conclusion
Using login_required with Django CBVs is simple once you know the rules. Do not decorate the class directly. Decorate dispatch with method_decorator, or use LoginRequiredMixin as the first base class.
Pick one style for your project and stay consistent. Set your login settings. Write two tests per protected view. That small routine will keep your app secure and your code clean.
Now you can protect any class-based view with confidence. Happy coding!