即使声明了字段,self.cleaned_data.get也不返回

时间:2019-04-27 22:42:32

标签: django

当我进入管理页面并尝试创建MyUser的新实例时,我无法创建它。当我打印出passwordconfirm_password时,我得到了password的正确值,但得到了None的{​​{1}}。

在我的confirm_password文件中,我具有以下内容:

admins.py

为什么class MyUserCreationForm(forms.ModelForm): """ A form for creating new users. """ password = forms.CharField(label='Password', widget=forms.PasswordInput) confirm_password = forms.CharField( label='Confirm password', widget=forms.PasswordInput) class Meta: models = MyUser fields = ('email', ) def clean_password(self): """ Check if two password entries match. """ password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if (password == confirm_password): return password else: raise forms.ValidationError("Passwords don't match") def save(self): """ Save the provided password in hash format. """ user = super().save(commit=False) user.set_password(self.cleaned_data['password']) user.save() return user 总是具有值confirm_password是什么原因?

1 个答案:

答案 0 :(得分:1)

您不应在clean_password中执行此代码。

在clean_confirm_password中执行此操作更有意义 这是从Django源代码中检索的片段:

def clean_confirm_password(self):
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("confirm_password")
        if password and confirm_password and password != confirm_password:
            #you can keep your simply Validation Error here
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
    return password2

并尝试保存:

 def save(self, commit=True):
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password"])
    if commit:
        user.save()
    return user

否则,您的代码似乎很好。 所以也许错误在其他地方。

在这里为您提供信息:https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L70