最初,报错的form表单验证部分如下:文章来源:https://www.toymoban.com/news/detail-547512.html
class ChangePwdForm(forms.Form):
password1 = forms.CharField(required=True, min_length=6)
password2 = forms.CharField(required=True, min_length=6)
def clean(self):
pwd1 = self.cleaned_data['password1']
pwd2 = self.cleaned_data['password2']
if pwd2 != pwd1:
raise forms.ValidationError("密码不一致")
return self.cleaned_data
经过查阅资料后发现,如果password1
字段不能满足定义的要求(最小六个字符长度)的话,就不会出现在cleaned_data
中,因此clean
方法在取值时发生错误。
根据上面的原理,我们只要先验证其是否在cleaned_data
中,再判断其是否相等就可以了。具体修改如下:文章来源地址https://www.toymoban.com/news/detail-547512.html
class ChangePwdForm(forms.Form):
password1 = forms.CharField(required=True, min_length=6)
password2 = forms.CharField(required=True, min_length=6)
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data and self.cleaned_data['password1'] != \
self.cleaned_data['password2']:
raise forms.ValidationError("密码不一致")
return self.cleaned_data
到了这里,关于【Django-报错处理】form.is_valid()方法报错:KeyError: ‘###‘的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!