gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:19:43 24 4
gpt4 key购买 nike

我扔ValidationError在验证我的 clean 中的数据时models.py 中的方法.如何在我的自定义 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

关于python - 在创建方法 django rest 框架中引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57776399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com