Set object-level permission with django-rest-framework

吃可爱长大的小学妹 提交于 2019-12-12 02:45:20

问题


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:


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



来源:https://stackoverflow.com/questions/41230236/set-object-level-permission-with-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!