Django:在其他装饰器中重复使用login_required装饰器 [英] Django: re-use login_required decorator inside other decorators
问题描述
根据 https://stackoverflow.com/a/8715790/210481 中的其中一项评论,同意,如果一个依赖另一个,我们应该避免使用多个装饰.
According to one of the comments in https://stackoverflow.com/a/8715790/210481, which I agree with, we should avoid multiple decorators if one depends on the other.
因此,在该示例中,如果我们为活动用户使用装饰器"active_required",则不必在同一视图上同时使用active_required和login_required.
So, in the example, if we have a decorator "active_required" for active users, we should not have to use both active_required and login_required on the same view.
我们应该在"active_required"中以某种方式将"login_required"修饰符称为".
We should have "login_required" decorator "called" somehow inside the "active_required" one.
是否可以使用django随附的标准"login_required"装饰器来做到这一点?
Is it possible to do it with the standard "login_required" decorator that comes with django?
我的要求是: 1)如果用户未通过身份验证,则应将其重定向到LOGIN_URL 2)如果用户已通过身份验证(通过了login_required),但未处于活动状态,则应将其重定向到页面以重新激活"他的帐户 3)如果用户已通过身份验证并处于活动状态,则该用户可以访问该视图
My requirements are: 1) if the user is not authenticated, I should redirect him to LOGIN_URL 2) if the user is authenticated (passed login_required), but is not active, I should redirect him to a page to "re-activate" his account 3) if the user is authenticated and active, the user can access the view
预先感谢
推荐答案
在考虑您的问题时,我发现首先创建一个简单的active_required
装饰器会更容易.这很容易,因为我们可以在django.contrib.auth.decorators
中使用user_passes_test
函数.
When thinking about your question, I found it easier to create a simple active_required
decorator first. This is very easy, because we can use the the user_passes_test
function in django.contrib.auth.decorators
.
然后问题变为如何将login_required
和active_required
组合到一个装饰器中?".我们需要定义一个函数:
The question then changes to "how do I combine the login_required
and active_required
into one decorator?". We need to define a function which:
- 以view函数作为参数
- 将两个装饰器都应用到它上以创建新的视图功能
- 返回新的视图功能
将它们放在一起,您将拥有以下内容:
Putting it all together, you have the following:
from django.contrib.auth.decorators import user_passes_test, login_required
active_required = user_passes_test(lambda u: u.is_active, login_url=REACTIVATE_URL)
def active_and_login_required(view_func):
decorated_view_func = login_required(active_required(view_func))
return decorated_view_func
这篇关于Django:在其他装饰器中重复使用login_required装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!