pythondjangorestdjango-rest-frameworkdjango-guardian

Set object-level permission with django-rest-framework


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?


Solution

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