[英]Difference between staff_member_required and user_passes_test
I've a doubt about the use of this two decorators.我对这两个装饰器的使用有疑问。 In my project I've some view in which I will allow the access only to the staff member.
在我的项目中,我有一些观点,我将只允许工作人员访问。 These are restricted area in which a staff can create a post or modify something about the user profile.
这些是限制区域,员工可以在其中创建帖子或修改有关用户配置文件的内容。 This area is the admin area of my web site but is not a default django admin.
此区域是我的 web 站点的管理区域,但不是默认的 django 管理员。 I've create a backend area that doesn't use django admin site.
我创建了一个不使用 django 管理站点的后端区域。
I've this view:我有这样的看法:
MODE 1模式 1
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required(login_url='login')
def staff_site(request):
some code here
MODE 2模式 2
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u:u.is_staff, login_url='login')
def staff_site(request):
some code here
What is the right way that I must use for my aim?我必须为我的目标使用的正确方法是什么?
They're both exactly the same.它们完全一样。 I would use
@staff_member_required
because it's less typing.我会使用
@staff_member_required
,因为它打字少。
Under the hood, Django uses user_passes_test
anyway, staff_member_required
is just a shortcut.在引擎盖下,Django 无论如何都使用
user_passes_test
, staff_member_required
只是一个快捷方式。 Here is the source code from Django:以下是 Django 的源代码:
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.