Login required
Protect a function view
from django.contrib.auth.decorators import (
login_required
)
@login_required
def profile(request):
return render(request, "profile.html")
Redirects anonymous users. The response goes to LOGIN_URL with a ?next= parameter pointing at the original path. See login_required.
Protect a class-based view
from django.contrib.auth.mixins import (
LoginRequiredMixin
)
from django.views.generic import TemplateView
class ProfileView(
LoginRequiredMixin, TemplateView
):
template_name = "profile.html"
Applies the same check. Put the mixin first in the base-class list so its dispatch runs before the view. See LoginRequiredMixin.
Set the login URL
settings.py
LOGIN_URL = "/login/"
Changes the redirect target. Point this at your login route; the default is /accounts/login/, and ?next=/profile/ is added automatically. See LOGIN_URL.
Related links
- Authentication (docs.djangoproject.com)
- Django cheatsheet (devhints.io)
0 Comments for this cheatsheet. Write yours!