Django:重写表单中的 clean() 方法 - 关于引发错误的问题
我一直在 clean 方法中做这样的事情:
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
raise forms.ValidationError('The start date cannot be later than the end date.')
但这意味着表单一次只能引发这些错误之一。有没有办法让表单引发这两个错误?
编辑#1: 上述任何解决方案都很棒,但希望能够在以下场景中工作:
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
raise forms.ValidationError('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
raise forms.ValidationError('The start date cannot be later than the end date.')
super(FooAddForm, self).clean()
其中 FooAddForm 是 ModelForm 并且具有也可能导致错误的独特约束。如果有人知道类似的事情,那就太好了......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自文档:
https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
From the docs:
https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
虽然是旧帖子,但如果您想要更少的代码,您可以使用
add_error()
方法来添加错误消息。我正在扩展@kemar的答案以显示使用的情况:add_error()
自动从cleaned_data字典中删除该字段,您不必手动删除它。此外,您无需导入任何内容即可使用它。
文档在这里
Although its old post, if you want less code you can use
add_error()
method to add error messages. I am extending the @kemar's answer to show the used case:add_error()
automatically removes the field from cleaned_data dictionary, you dont have to delete it manually.Also you dont have to import anything to use this.
documentation is here
如果您希望将错误消息附加到表单而不是特定字段,您可以使用键“
__all__
”,如下所示:另外,正如 Django 文档所解释的:“如果您想要要向特定字段添加新错误,您应该检查该键是否已存在于
self._errors
中,如果不存在,则为给定键创建一个新条目,并保存一个空的。无论哪种情况,您都可以将错误消息附加到相关字段名称的列表中,并在显示表单时显示该消息。”
If you'd prefer that the error messages be attached to the form rather than to specific fields, you can use the key "
__all__
" like this:Also, as the Django docs explain: "if you want to add a new error to a particular field, you should check whether the key already exists in
self._errors
or not. If not, create a new entry for the given key, holding an emptyErrorList
instance. In either case, you can then append your error message to the list for the field name in question and it will be displayed when the form is displayed."