It's a really simple form but I don't know where's got wrong. When I check the debug mode of django site, I found that the clean_data of new field is missing, as the picture of following:
class PasswordEditForm(forms.Form):
old = forms.CharField(widget=forms.PasswordInput, min_length=6,
max_length=30, label='舊密碼', label_suffix=' ')
new = forms.CharField(widget=forms.PasswordInput, min_length=6,
max_length=30, label='新密碼', label_suffix=' ')
new_confirm = forms.CharField(widget=forms.PasswordInput, min_length=6,
max_length=30, label='再輸入一次', label_suffix=' ')
def clean_new(self):
cd = self.cleaned_data
if cd['old'] == cd['new']:
raise forms.ValidationError('新密碼與舊密碼相同')
return cd['new']
def clean_new_confirm(self):
cd = self.cleaned_data
if cd['new'] != cd['new_confirm']:
raise forms.ValidationError('兩次輸入密碼不相符')
return cd['new_confirm']
![cleaned_data['new'] is missing](https://i.stack.imgur.com/ByUxT.jpg)
The problem is if you type same new and old password then
clean_newmethod raise exception and return no value. That's why inclean_new_confirmwhich performed afterclean_newcleaned_data is not containsnewvalue.You can avoid error just using
get. Check first if cleaned_data containsnewvalue and if yes, check ifnewequals tonew_confirm: