同时使用 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 页面.如何实现同时使用两个 mixin 但同时它们都围绕变量 login_url 发生冲突.不幸的是 UserPassesTestMixin 使用相同的 login_url 所以这给我带来了麻烦.
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屋!