Search code examples
djangoresttastypie

PATCH updates the data for a model, but responds with a 401 Unauthorized error


Here's my Model:

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) 

Here's my 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
        }

You can see that there's no checks being done to authorise or authenticate the user at this time, so why when I send a PATCH request, it all goes through fine, but responds with a Unauthorized error?

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

Am I doing something wrong here? I can't see what the server is doing to say that the user is unauthorised, but hey ho.

Edit: Silvio gave me the nudge to work it out, the related resource GroupMembershipResource was not set up with the same Authorization, so it was defaulting to read only. Therefore I could change the name but then not see it as the other resource was stopping me.


Solution

  • Ensure that you have applied the same Authorization in the related resource GroupMembershipResource, otherwise, the inherit authorization will be readonly:

    class GroupMembershipResource(ModelResource): ...

    class Meta:
        authorization = Authorization()