问题描述
我不知道为什么要求装饰器的权限不工作。我想允许访问工作人员的视图。我试过
I can't figure out why the permission required decorator isn't working. I would like to allow access to a view only for staff members. I have tried
@permission_required('request.user.is_staff',login_url="../admin")
def series_info(request):
...
还有
@permission_required('user.is_staff',login_url="../admin")
def series_info(request):
...
作为超级用户,我可以访问视图,但是我创建的任何用户无法访问它,并被重定向到登录URL页面。我测试了login_required的装饰器,并且工作正常。
As the superuser, I can access the view, but any users I create as staff can't access it and are redirected to the login url page. I tested the login_required decorator and that works fine.
推荐答案
permission_required()
必须传递一个权限名,而不是一个字符串中的Python表达式。尝试这样做:
permission_required()
must be passed a permission name, not a Python expression in a string. Try this instead:
from contrib.auth.decorators import user_passes_test
def staff_required(login_url=None):
return user_passes_test(lambda u: u.is_staff, login_url=login_url)
@staff_required(login_url="../admin")
def series_info(request)
...
重新阅读您发布的链接; permission_required()
将测试用户是否被授予特定权限。它不会测试用户对象的属性。
Re-read the links you posted; permission_required()
will test if a user has been granted a particular permission. It does not test attributes of the user object.
从:
def vote(request):
if request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
# vote here
else:
return HttpResponse("You can't vote in this poll.")
#
#
# # #
###
#
def user_can_vote(user):
return user.is_authenticated() and user.has_perm("polls.can_vote")
@user_passes_test(user_can_vote, login_url="/login/")
def vote(request):
# vote here
#
#
# # #
###
#
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote', login_url="/login/")
def vote(request):
# vote here
这篇关于permission_required装饰器不适用于我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!