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?

Luke Skywalker
  • 1,464
  • 3
  • 17
  • 35

1 Answers1

3

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

phoenix
  • 7,988
  • 6
  • 39
  • 45
Mad Wombat
  • 14,490
  • 14
  • 73
  • 109