from django.conf import settings from django.shortcuts import redirect def my_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) # ...
from django.shortcuts import render def my_view(request): if not request.user.is_authenticated: return render(request, 'myapp/login_error.html') # ...
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
next_to = request.GET.get('next', None) # 獲取是否有next的重定向,是一個相對路徑,不含方案和域名 if next_to: return redirect(next_to)
if user.is_active: # 若用戶是活躍的,即未凍結的,在1.10以前凍結用戶默認也能登陸,因此須要本身認證 login(request, user) # 登陸 ...... #其餘處理 else: return HttpResponse('用戶被凍結')
from django.contrib.admin.views.decorators import staff_member_required @staff_member_required def my_view(request): ...
from django.shortcuts import redirect def my_view(request): if not request.user.email.endswith('@example.com'): return redirect('/login/?next=%s' % request.path) # ...
from django.contrib.auth.decorators import user_passes_test def email_check(user): return user.email.endswith('@example.com') @user_passes_test(email_check) def my_view(request): ...
from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to'
from django.contrib.auth.mixins import UserPassesTestMixin class MyView(UserPassesTestMixin, View): def test_func(self): return self.request.user.email.endswith('@example.com')