I have written a validate() function inside my serializer. By default, Serializer Errors return 400 as a status code. But I want to return 404. I tried this:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = models.MyClass
fields = "__all__"
def validate(self, data):
current_user = self.context.get("request").user
user = data.get("user")
if user!=current_user:
raise ValidationError({'detail': 'Not found.'}, code=404)
return data
But it still returns 400 as a response in status code. How to do it?
You can do it from view by handling the serializes validation:
Alternately you can do it by defining own exception handler:
But as you said, if you want to do it from serializer, then you have to define custom exception and raise it from serialize :