我对依赖于多个字段的表单进行了验证检查,但最好让验证错误向用户具体显示哪些字段导致了问题,而不仅仅是表单顶部的错误消息。 (该表单有很多字段,因此可以更清楚地具体显示错误所在)。
作为解决方法,我尝试在每个相关字段中创建相同的验证clean_field()
方法,以便用户会在这些字段旁边看到错误。但是我似乎只能从以下位置访问该特定字段self.cleaned_data
而不是其他的?
或者,是否可以从表单中引发字段错误clean()
method?
尝试1:
def clean_supply_months(self):
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
raise forms.ValidationError('Please specify time at address if less than 3 years.')
def clean_supply_years(self):
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_years'):
raise forms.ValidationError('Please specify time at address if less than 3 years.')
def clean_same_address(self):
.....
如果您想访问多个字段的清理数据,您应该使用clean
方法而不是clean_<field>
方法。这add_error() https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.Form.add_error方法允许您将错误分配给特定字段。
例如,要添加请注明地址时间错误消息至same_address
领域,你会这样做:
def clean(self):
cleaned_data = super(ContactForm, self).clean()
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
self.add_error('same_address', "Please specify time at address if less than 3 years.")
return cleaned_data
请参阅文档验证相互依赖的字段 https://docs.djangoproject.com/en/1.11/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)