permission_required decorator not working for me

前端 未结 5 1120
长情又很酷
长情又很酷 2021-02-04 18:24

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         


        
5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 18:42

    Here is an example of behavior I don't understand. I create a user, request and decorate a test function with permission_required checking for 'is_staff'. If the user is superuser, then access is granted to the test function. If the user only has is_staff = True, access is not granted.

    from django.http import HttpRequest
    from django.contrib.auth.models import User
    from django.contrib.auth.decorators import permission_required
    
    @permission_required('is_staff')
    def test(dummy='dummy'):
        print 'In test'
    
    mb_user = User.objects.create_user('mitch', 'mb@home.com', 'mbpassword')
    mb_user.is_staff = True
    
    req = HttpRequest()
    req.user = mb_user
    
    test(req) # access to test denied - redirected
    
    req.user.is_staff = False
    
    test(req) # same as when is_staff is True
    
    req.user.is_superuser = True
    test(req) # access to test allowed
    

提交回复
热议问题