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
来自文档:
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)
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)
| 归档时间: |
|
| 查看次数: |
11152 次 |
| 最近记录: |