最初,报错的form表单验证部分如下:

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中,再判断其是否相等就可以了。具体修改如下:

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