我在models.py
中验证clean
方法中的数据时抛出ValidationError
。如何在我的自定义create
方法中捕获此错误,以便它抛出一个包含错误详细信息的 json 对象 道路
{
"detail":"input is not valid"
}
#models.py
class Comment(models.Model):
text = models.CharField(max_length=256)
commenter = models.ForeignKey(User, on_delete=models.SET_NULL)
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
def clean(self, *args, **kwargs):
if containsBadWords(text):
raise ValidationError(_("Be Polite"))
#serializer.py
def create(self, validated_data):
request = self.context.get('request', None)
commenter = request.user
try:
obj = Comment.objects.create(
post = validated_data['post'],
commenter = commenter,
text = validated_data['text']
)
except ValidationError as ex:
raise ex
return obj
检查你扔了serializers.ValidationError
不是ValidationError
django.core.exceptions
。您可以通过以下方式更改create
方法:
def create(self, validated_data):
request = self.context.get('request', None)
commenter = request.user
try:
obj = Comment.objects.create(
post = validated_data['post'],
commenter = commenter,
text = validated_data['text']
)
except ValidationError as ex:
raise serializers.ValidationError({"detail": "input is not valid"})
return obj