Django Rest Framework Object Level Permission on POST

I want request.user to only be able to issue a POST request to create a forum topic in which they are authors. With PUT and DELETE, I can achieve this using has_object_permission , but with POST I cannot do this, I assume, because the object has not been created yet.

 class TopicPermission(IsAuthenticatedOrReadOnly): """ Any user should be able to read topics but only authenticated users should be able to create new topics. An owner or moderator should be able to update a discussion or delete. """ def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True # Instance must have an attribute named `author` or moderator return obj.author == request.user or request.user.forum_moderator 

How can I check request.user == obj.author in POST requests?

+7
django django-rest-framework
source share
1 answer

I ended up checking in the view instead of the serializer:

 class TopicViewSet(viewsets.ModelViewSet): permission_classes = (TopicPermission, ) queryset = Topic.objects.all() serializer_class = TopicSerializer def create(self, request, *args, **kwargs): """ verify that the POST has the request user as the 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) 
+3
source share

All Articles