If the user is not authenticated, they are redirected to settings.LOGIN_URL with the ?next=/current-url/ parameter.
Decorator for FBVs
from django.contrib.auth.decorators import login_required
@login_required
def my_profile(request):
return render(request, 'profile.html', {'user': request.user})
# Custom login URL
@login_required(login_url='/custom/login/')
def secret_view(request):
...
If the user is not authenticated, they are redirected to settings.LOGIN_URL with the ?next=/current-url/ parameter.
LoginRequiredMixin for CBVs
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
class TaskListView(LoginRequiredMixin, ListView):
model = Task
template_name = 'tasks/list.html'
login_url = '/accounts/login/' # where to redirect
redirect_field_name = 'next' # GET parameter name
The mixin must come first in the list of parent classes.
settings.LOGIN_URL
# settings.py
LOGIN_URL = '/accounts/login/' # default
LOGIN_REDIRECT_URL = '/' # after successful login
LOGOUT_REDIRECT_URL = '/accounts/login/' # after logout
Checking authentication inside a view
def my_view(request):
if not request.user.is_authenticated:
return redirect('login')
# code below only runs for authenticated users
UserPassesTestMixin — custom conditions
from django.contrib.auth.mixins import UserPassesTestMixin
class AdminOnlyView(UserPassesTestMixin, ListView):
model = Task
def test_func(self):
return self.request.user.is_staff # staff only
def handle_no_permission(self):
return redirect('home') # custom redirect on denial
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!