检查表单有效后,我会执行其他验证:
def reset_passwd(req):
if req.method == 'POST':
form = ResetPasswdForm(req.POST)
if form.is_valid():
# extract data
passwd1 = form.cleaned_data['passwd1']
passwd2 = form.cleaned_data['passwd2']
# validate passwd
if passwd1 != passwd2:
raise forms.ValidationError('passwords are not the same', 'passwd_mismatch')
# do stuff...
return HttpResponseRedirect('/success')
else:
form = ResetPasswdForm(req.POST)
return render(req, 'reset_passwd_form.html', {'form': form})
问题是提出ValidationError
Exception
当然会中断视图函数的执行,因此不会返回任何响应!
如何回复显示验证错误的绑定表单,以便验证不由form.is_valid()
执行?
(令人困惑的是django文档说form.is_valid()
如果表单无效则会抛出ValidtionError
,但是当它is_valid()
为假时,它必须将它们作为调试它继续执行。)
答案 0 :(得分:2)
要验证此类情况,您应该使用表单的clean()
方法,而不是在视图中引发错误。
答案 1 :(得分:0)
您需要覆盖is_valid()方法,首先调用super is_valid()(如果返回false则返回false),然后处理错误情况。
如果你使用clean()而不是因为" required = True"在您的其他领域,将需要手动检查所有内容。 super()。clean()只是...不会检查它afaik,它可以在访问cleaning_data [' passwd1']时给你KeyError,除非你自己检查。
class MyResetPasswdForm(forms.Form):
passwd1 = forms.CharField(widget=forms.PasswordInput, required=True)
passwd2 = forms.CharField(widget=forms.PasswordInput, required=True)
def is_valid(self):
valid = super(MyResetPasswdForm).is_valid()
if not valid:
return valid
if self.cleaned_data.get("passwd1") != self.cleaned_data.get("passwd2"):
# You cannot raise a ValidationError because you are not in the clean() method, so you need to add the error through the add_error method.
self.add_error("passwd2", ValidationError('passwords are not the same', 'passwd_mismatch')
# You could also use None instead of "passwd2" if you do not want the error message to be linked to the field.
if not self.errors:
return True
return False
这样,你得到预设的错误信息,当你调用super()。is_valid()时,django会处理字段要求。