9

我一直在 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 并且具有也可能导致错误的独特约束。如果有人知道这样的事情,那就太好了......

4

4 回答 4

18

从文档:

https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

from django.forms.util import ErrorList

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self._errors['type'] = ErrorList([msg])
    del self.cleaned_data['type']

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self._errors['start'] = ErrorList([msg])
    del self.cleaned_data['start']

  return self.cleaned_data
于 2010-01-22T13:41:41.747 回答
7
errors = []
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
      errors.append('The type and organization do not match.')
if self.cleaned_data['start'] > self.cleaned_data['end']:
     errors.append('The start date cannot be later than the end date.')

if errors:
    raise forms.ValidationError(errors)
于 2010-01-22T12:59:03.393 回答
3

如果您希望将错误消息附加到表单而不是特定字段,则可以使用键“ __all__”,如下所示:

msg = 'The type and organization do not match.'
self._errors['__all__'] = ErrorList([msg])

此外,正如 Django 文档所解释的:“如果您想向特定字段添加新错误,则应检查该键是否已存在self._errors。如果不存在,请为给定键创建一个新条目,并保存一个空ErrorList实例. 在任何一种情况下,您都可以将错误消息附加到相关字段名称的列表中,并在显示表单时显示。”

于 2010-03-09T00:49:50.067 回答
3

虽然它是旧帖子,但如果您想要更少的代码,您可以使用add_error()方法添加错误消息。我正在扩展@kemar 的答案以显示用例:

add_error()自动从 clean_data 字典中删除该字段,您不必手动删除它。你也不必导入任何东西来使用它。

文档在这里

def clean(self):

  if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']:
    msg = 'The type and organization do not match.'
    self.add_error('type', msg)

  if self.cleaned_data['start'] > self.cleaned_data['end']:
    msg = 'The start date cannot be later than the end date.'
    self.add_error('start', msg)

  return self.cleaned_data
于 2018-02-02T08:10:20.567 回答