Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework - ValidationError raised in models' save method. How to pass error to http response

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)?

like image 963
Alex Avatar asked Oct 20 '25 12:10

Alex


1 Answers

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
like image 149
whitehat Avatar answered Oct 23 '25 04:10

whitehat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!