为什么cleaning_data中没有字段?

时间:2014-05-13 21:56:38

标签: django django-forms

我有表格:

class ChangePasswordForm(forms.Form):
    oldpassword = forms.CharField(
        min_length=5,
        label=_('Old password'),
        widget=forms.PasswordInput(),
    )
    password1 = forms.CharField(
        min_length=5,
        label=_('Password'),
        widget=forms.PasswordInput(),
    )
    password2 = forms.CharField(
        min_length=5,
        label=_('Retype'),
        widget=forms.PasswordInput(),
    )

    def clean(self):
        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
            raise forms.ValidationError(_('The new passwords must be the same'))
        else:
            return self.cleaned_data

如果我输入所有字段,我会收到POST:

{u'password1': [u'ewrtrwetwe'], u'csrfmiddlewaretoken': [u'2gEAqLjaKC5NgMZrE6Brd9p3vThUC10w'], u'oldpassword': [u'wertwertwet'], u'password2': [u'tewrtwertwert']}

和cleaning_data:

{'password1': u'ewrtrwetwe', 'password2': u'tewrtwertwert', 'oldpassword': u'wertwertwet'}

但是如果我在password1和password2输入中键入相同的文本,我会收到POST:

{u'password1': [u'1234'], u'csrfmiddlewaretoken': [u'2gEAqLjaKC5NgMZrE6Brd9p3vThUC10w'], u'oldpassword': [u'wertwertwet'], u'password2': [u'1234']}

和cleaning_data:

{'oldpassword': u'wertwertwet'}

我收到错误:

if self.cleaned_data['password1'] != self.cleaned_data['password2']:
KeyError: 'password1'

为什么?

1 个答案:

答案 0 :(得分:0)

您的cleaned_data方法未获得clean()。你需要写得更像这样:

def clean(self):
    cleaned_data = super(ChangePasswordtForm, self).clean()
    # Do things
    return cleaned_data

此外,即使您return cleaned_data(django 1.7 +不再适用),您也应始终raise ValidationError