Set object-level permission with django-rest-frame

2019-09-04 19:55发布

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?

1条回答
等我变得足够好
2楼-- · 2019-09-04 20:42

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

查看更多
登录 后发表回答