gpt4 book ai didi

django - Permission_required 装饰器不适合我

转载 作者:行者123 更新时间:2023-12-02 02:04:21 25 4
gpt4 key购买 nike

我不明白为什么需要权限的装饰器不起作用。我想只允许工作人员访问 View 。我已经尝试过了

@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):
...

作为 super 用户,我可以访问该 View ,但我作为员工创建的任何用户都无法访问该 View ,并且会被重定向到登录 URL 页面。我测试了 login_required 装饰器,效果很好。

最佳答案

permission_required() 必须传递权限名称,而不是字符串中的 Python 表达式。试试这个:

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)
...
<小时/>

Thanks. That does work. Do you have an example of how to use permission_required? From the documentation docs.djangoproject.com/en/1.0/… and djangobook.com/en/2.0/chapter14 I thought what I had should work.

重新阅读您发布的链接; permission_required() 将测试用户是否已被授予特定权限。它不测试用户对象的属性。

来自http://www.djangobook.com/en/2.0/chapter14/ :

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

关于django - Permission_required 装饰器不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1269444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com