如何在Django中正确抛出ValidationError? [英] How to properly throw a ValidationError in Django?
问题描述
以Django形式引发ValidationError异常的适当方法是什么?
What's the appropriate way to throw a ValidationError exception in a Django form?
似乎有几种不同的互斥方式引发此异常.如果我在表单中有一个自定义的 clean()
方法,并且该错误没有涉及任何特定字段,那么我必须将其抛出:
There seems to be a few different mutually-exclusive ways to throw this exception. If I have a custom clean()
method in a form, and the error doesn't refer to any specific field, then I have to throw it like:
raise ValidationError({NON_FIELD_ERRORS: ["Something's wrong!"]})
但是,如果我在InlineFormSet的自定义 clean()
方法中执行此操作,它将破坏Django的验证框架并引发错误:
However, if I do this inside a custom clean()
method of an InlineFormSet, it breaks Django's validation framework and throws the error:
AttributeError: 'ValidationError' object has no attribute 'error_list'
如果我改为将代码更改为:
If I instead change my code to:
raise ValidationError("Something's wrong!")
然后它可以正常工作,并且在我的网页上看到一个很好的用户友好的红色验证错误.但是,这种语法几乎在其他任何地方都会失败,并且如果我不不使用 raise ValidationError时,会错误地抛出错误
语法.为什么会这样?'ValidationError'对象没有属性'error_list'
({...})
then it works just fine and I see a nice user-friendly red validation error on my web page. However, this syntax fails almost anywhere else, and confusingly throws the error 'ValidationError' object has no attribute 'error_list'
if I don't use the raise ValidationError({...})
syntax. Why is this?
推荐答案
在任何继承自BaseFormSet的类中,在 clean
实例方法中引发的 ValidationError
不相关具有任何特定形式.
In any class that inherits from BaseFormSet, ValidationError
s raised in the clean
instance method are not associated with any particular form.
根据设计,您可以将列表传递给 ValidationError
或InlineFormSet的 clean
中的字符串.这将确保 self.error_list
已设置.这对于表单集很有意义,因为它包含表单列表.
By design, you can pass a list to ValidationError
or a string in clean
for InlineFormSet. This will ensure that self.error_list
is set. This makes sense for formset because it contains a list of forms.
raise ValidationError([{NON_FIELD_ERRORS: ["Something's wrong!"]}])
这与在 Form
中引发的 ValidationError
不同,在该表单中引发的错误与该表单相关联.因此,表单支持通过 dict
, str
或 list
到ValidationError.
This is different for ValidationError
raised in a Form
where errors raised are associated with that form. For this reason, forms support passing dict
, str
or list
to ValidationError.
这篇关于如何在Django中正确抛出ValidationError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!