Alex
Alex

Reputation: 2402

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

Upvotes: 4

Views: 6011

Answers (2)

Chiefir
Chiefir

Reputation: 2671

You can write your custom error, like this:

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_400_BAD_REQUEST

class MyError(APIException):
    """Readers error class"""
    def __init__(self, msg):
        APIException.__init__(self, msg)
        self.status_code = HTTP_400_BAD_REQUEST
        self.message = msg

And return any status code what you want.

You can use it normally where you want like this:

raise MyError({"detail": "You did something wrong!"})

Upvotes: 3

Sreekanth Reddy Balne
Sreekanth Reddy Balne

Reputation: 3424

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

Upvotes: 9

Related Questions