In a django rest framework app, there's a TextViewSet. The Text object structure is as follows:
{
text: text_value,
author: author_id
}
When creating a new Text instance, I want to check if the supplied author_id equals the currently logged-in user's id.
I've read this question: When to use Serializer's create() and ModelViewset's perform_create(), but still can't decide whether to override Serializer's create(), ModelViewset's create() or perform_create() methods. What's the right method to override?
UPD:
models.py:
class Text(models.Model):
text = models.TextField()
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
serializers.py:
class TextSerializer(serializers.ModelSerializer):
class Meta:
model = Text
fields = ['author', 'text']
The question is in which of these methods should one perform this check if self.request.user.id != self.request.data['author']:
?
CodePudding user response:
You can override create()
the method of your TextViewSet
views.py
from rest_framework.response import Response
class TextViewSet(ModelViewSet):
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
if request.user.id == request.data['author']:
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
else:
return Response("Unauthorized", status=status.HTTP_401_UNAUTHORIZED