Set object-level permission with django-rest-framework
Asked Answered
I

1

2

Trying to manage django-guardian object-level permissions with django-rest-framework the most cleanly and canon possible.

I want to assign a read permission (module.view_object) of an object to to the user making the request when performing a POST.

My class-based view:

class ObjectList(ListCreateAPIView):
  queryset = Object.objects.all()
  serializer_class = ObjectSerializer
  filter_backends = (DjangoObjectPermissionsFilter,)
  # MyObjectPermissions inherit from DjangoObjectPermissions and just 
  # add the 'view_model' permission
  permission_classes = (MyObjectPermissions,)

  def perform_create(self, serializer):
    serializer.save(owner=self.request.user)

As described in the django-rest-framework documentation, I've overloaded perform_create in order to pass the user to the serializer.

But how do I assign the permission (using guardian.shortcuts.assign_perm) in the serializer. Is there no other way but to override the save method to assign the permission manually? Isn't there some kind of standard mechanism to manage a common behavior as this one?

Iniquitous answered 19/12, 2016 at 20:9 Comment(2)
You could assign the permission in the perform_create(). serializer.save() method returns the instance that was saved, you knowSaundra
I would accept you answer.Iniquitous
S
3

You can assign the permission in the perform_create() method of the ViewSet.

Saundra answered 19/1, 2017 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.