当我进入管理页面并尝试创建MyUser
的新实例时,我无法创建它。当我打印出password
和confirm_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
是什么原因?
答案 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