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']
The problem is if you type same new and old password then clean_new
method raise exception and return no value. That's why in clean_new_confirm
which performed after clean_new
cleaned_data is not contains new
value.
You can avoid error just using get
. Check first if cleaned_data contains new
value and if yes, check if new
equals to new_confirm
:
def clean_new_confirm(self):
cd = self.cleaned_data
new_pass = cd.get('new')
if new_pass and new_pass != cd.get('new_confirm'):
raise forms.ValidationError('兩次輸入密碼不相符')
return cd['new_confirm']