同时使用LoginRequiredMixin和UserPassesTestMixin [英] Use LoginRequiredMixin and UserPassesTestMixin at the same time
问题描述
我想要一个同时使用LoginRequiredMixin和UserPassesTestMixin的TemplateView类.像这样:
I want to have a TemplateView Class that uses LoginRequiredMixin and UserPassesTestMixin at the same time. Something like this:
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class FinanceOverview(LoginRequiredMixin, UserPassesTestMixin, TemplateMixin):
login_url = '/login'
redirect_field_name = 'next'
def test_func(self):
return self.request.user.groups.filter(name="FinanceGrp").exists()
def get(self, request, *args, **kwargs):
DO SOMETHING IF USER IS AUTHENTICATED AND ALSO MEMBER OF GROUP FinanceGrp
基本上如上所述,我要实现的目标是:
Basically as you can see above, what I want to achieve is the following:
-
如果用户未通过身份验证,则将用户重定向到:
If user is not authenticated, to redirect user to:
https://website/login?next=financeoverview
但是我不知道如何将经过身份验证但不属于组 FinanceGrp 的用户重定向到另一个页面.例如:
However what I can't figure out is how to redirect users who are authenticated but do not belong to group FinanceGrp to another page. For example:
https://website.com/access_denied?previous_page=financeoverview
在我的情况下,用户在组测试失败时总是被重定向到/login页面.我如何才能实现同时使用两个但同时又都在变量login_url冲突的mixin.不幸的是,UserPassesTestMixin使用的登录名相同,所以给我带来了麻烦.
In my case users are always redirected to /login page when they fail the group test. How can I achieve two mixins used at the same time but at the same time both of them are clashing around variable login_url. Unfortunately UserPassesTestMixin is using the same login_url so it makes this trouble for me.
预先感谢
米洛斯
推荐答案
我认为最好还是将AccessMixin
子类化,然后自己执行这些检查.像这样:
I think you're better off subclassing AccessMixin
and then performing these checks yourself. Something like this:
from django.contrib.auth.mixins import AccessMixin
from django.http import HttpResponseRedirect
class FinanceOverview(AccessMixin, TemplateMixin):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
# This will redirect to the login view
return self.handle_no_permission()
if not self.request.user.groups.filter(name="FinanceGrp").exists():
# Redirect the user to somewhere else - add your URL here
return HttpResponseRedirect(...)
# Checks pass, let http method handlers process the request
return super().dispatch(request, *args, **kwargs)
这篇关于同时使用LoginRequiredMixin和UserPassesTestMixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!