我正在使用带有ModelViewset的django rest框架:
class FooViewset(viewsets.ModelViewSet):
serializer_class = FooSerializer
queryset = Foo.objects.all()
和ModelSerializer:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = [
"id",
"bar",
"baz",
]
我还有模型的保存方法:
class Foo(models.Model):
...
def save(self):
if condition:
raise ValidationError("Illegal parameters")
return super().save(*args, **kwargs)
当触发此验证错误时,drf将向前端发送500响应,不发送任何文本。如何获取带有“ ValidationError”(非法参数)中文本的“错误请求”响应?
答案 0 :(得分:1)
from rest_framework import serializers
class Foo(models.Model):
...
def save(self):
if condition:
raise serializers.ValidationError("Illegal parameters")
return super().save(*args, **kwargs)
我还没有测试过。
相反,我建议在序列化程序类的create
方法中执行此操作。
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
答案 1 :(得分:1)
您可以这样编写自定义错误:
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
并返回您想要的任何状态代码。
您可以像这样正常使用它:
raise MyError({"detail": "You did something wrong!"})