Django:覆盖表单中的clean()方法 - 关于引发错误的问题

Mon*_*lik 9 django django-forms django-validation

我一直在干净的方法中做这样的事情:

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.')
Run Code Online (Sandbox Code Playgroud)

但那意味着表单一次只能引发其中一个错误.表单有没有办法提出这两个错误?

编辑#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()
Run Code Online (Sandbox Code Playgroud)

其中FooAddForm是ModelForm并且具有可能也会导致错误的唯一约束.如果有人知道这样的事情那会很棒......

kem*_*mar 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
Run Code Online (Sandbox Code Playgroud)


Dan*_*man 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)
Run Code Online (Sandbox Code Playgroud)