在创建方法 django rest 框架中引发错误



我在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不是ValidationErrordjango.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

相关内容

  • 没有找到相关文章

最新更新