PATCH更新模型的数据,但响应401 Unauthorized错误

时间:2016-05-22 19:37:22

标签: django rest tastypie

这是我的模特:

class EmployeeGroup(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(EmployeeProfile, 
                                related_name='employee_groups', 
                                through='GroupMembership')
    parent_group = models.ForeignKey('self', 
                                related_name='children', 
                                blank=True, null=True) 

这是我的ModelResource:

class EmployeeGroupResource(ModelResource):
    parent_group = fields.ForeignKey('self', 'parent_group', null=True)
    members = fields.ToManyField(GroupMembershipResource, 
         attribute = lambda bundle: bundle.obj.members.through.objects.filter(group=bundle.obj) or bundle.obj.members, full=True)

    class Meta:
        queryset = EmployeeGroup.objects.all()
        resource_name = 'employee-groups'
        authentication = Authentication()
        authorization = Authorization()
        filtering = {
            'members': ALL_WITH_RELATIONS
        }

您可以看到此时没有对用户进行授权或身份验证的检查,那么为什么当我发送PATCH请求时,一切都很顺利,但是会以未经授权的错误响应?

curl --dump-header - -H "Content-Type: application/json" 
    -X PATCH --data '{"name": "human resources"}' 
    http://localhost:8000/api/v1/employee-groups/12/

HTTP/1.0 401 Unauthorized
Date: Sun, 22 May 2016 19:28:31 GMT
Server: WSGIServer/0.2 CPython/3.5.1
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8

我在这里做错了吗?我无法看到服务器正在做什么来说用户是未经授权的,但是嘿嘿。

修改 Silvio给了我推动它的工作,相关资源GroupMembershipResource没有设置相同的授权,所以它默认为只读。因此,我可以更改名称但不会看到它,因为其他资源阻止了我。

1 个答案:

答案 0 :(得分:1)

确保您在相关资源Authorization中应用了相同的GroupMembershipResource,否则,继承授权将是只读的:

class GroupMembershipResource(ModelResource):     ...

class Meta:
    authorization = Authorization()