I'm using the django rest framework, with a ModelViewset:
class FooViewset(viewsets.ModelViewSet):
serializer_class = FooSerializer
queryset = Foo.objects.all()
and a ModelSerializer:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = [
"id",
"bar",
"baz",
]
I also have the model's save method:
class Foo(models.Model):
...
def save(self):
if condition:
raise ValidationError("Illegal parameters")
return super().save(*args, **kwargs)
When this validation error is triggered, drf, sends a 500 response to the frontend, with no text. How do I get it to instead give a 'bad request' response, with the text in the ValidationError (Illegal parameter)?
from rest_framework import serializers
class Foo(models.Model):
...
def save(self):
if condition:
raise serializers.ValidationError("Illegal parameters")
return super().save(*args, **kwargs)
I have not tested this.
Instead, I would recommend doing this inside your serializer class's create method.
from rest_framework import serializers
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = [
"id",
"bar",
"baz",
]
def create(self, validated_data):
if condition:
raise serializers.ValidationError("Illegal parameters")
instance = super(FooSerializer, self).create(validated_data)
instance.save()
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With