Reputation: 2671
How can I validate an additional arguments passed like this:
class MyViewSet(MultiSerializerViewSet):
# some stuff
def perform_create(self, serializer):
serializer.save(creator=self.request.user)
How can I validate a creator
in the serializer?
Upvotes: 1
Views: 2413
Reputation: 5482
You can not validate fields passed as arguments to serializer.save() method, they will only be available in create method of the serializer, and I suggest not to run validations there. What I do in these kind of situations is, I override the create method of the viewset, and add extra parameters to the data I pass to the serializer.
class MyViewSet(MultiSerializerViewSet):
def create(self, request, *args, **kwargs):
request_data = request.data
request_data['creator'] = self.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=status.HTTP_201_CREATED, headers=headers)
With this setup, you also need to add creator as a serializer field. With this, the field will be alailable in validtion flow.
Upvotes: 2