Django Rest Framework object level permission on POST -
i want make sure request.user can issue post request create forum topic in auther. put , delete i'm able achieve using has_object_permission
post i'm not able that, i'm guessing because object hasn't been created yet.
class topicpermission(isauthenticatedorreadonly): """ user should able read topics authenticated users should able create new topics. owner or moderator should able update discussion or delete. """ def has_object_permission(self, request, view, obj): if request.method in safe_methods: return true # instance must have attribute named `author` or moderator return obj.author == request.user or request.user.forum_moderator
how go verifying request.user == obj.author
in post requests?
i ended doing validation in viewset instead of serializer:
class topicviewset(viewsets.modelviewset): permission_classes = (topicpermission, ) queryset = topic.objects.all() serializer_class = topicserializer def create(self, request, *args, **kwargs): """ verify post has request user obj.author """ if request.data["author"] == str(request.user.id): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=true) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return response(serializer.data, status=201, headers=headers) else: return response(status=403)
Comments
Post a Comment