permission_required装饰器不适用于我 [英] permission_required decorator not working for me

查看:160
本文介绍了permission_required装饰器不适用于我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么要求装饰器的权限不工作。我想允许访问工作人员的视图。我试过

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?从
文档
docs.djangoproject.com/en/1.0/...和
djangobook.com/en/2.0/chapter14 I
认为我应该工作。 p>

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()将测试用户是否被授予特定权限。它不会测试用户对象的属性。

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.

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

这篇关于permission_required装饰器不适用于我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆