# 认证装饰器 class AuthDecorator(object): @method_decorator(login_required(login_url="/login/")) def dispatch(self, request, *args, **kwargs): return super(AuthDecorator, self).dispatch(request, *args, **kwargs) def has_auth(func): def auth(request, *args, **kwargs): if not request.session.get("username"): return redirect(reverse("login")) return func(request, *args, **kwargs) return auth @has_auth def index(request): user = request.session.get("username") business_obj = Business.objects.all() user_obj = User.objects.all() hosts = Host.objects.filter(user__username=user) return render(request, "index.html", { "hosts": hosts, "business_obj": business_obj, "user_obj": user_obj })
类装饰器
# 认证装饰器 class Auth(View): def dispatch(self, request, *args, **kwargs): user_obj = UserInfo.objects.filter(username=request.session.get("username")).first() if not user_obj: return redirect(reverse("login")) return super(Auth, self).dispatch(request, *args, **kwargs) # 主页视图 class IndexView(Auth): def get(self, request): user = request.session.get("username") business_obj = Business.objects.all() user_obj = UserInfo.objects.all() hosts = Host.objects.filter(user__username=user) return render(request, "index.html", { "hosts": hosts, "business_obj": business_obj, "user_obj": user_obj })