我已经成功创建并扩展了 UserCreationForm
以获得 email
、 first_name
和 last_name
。它在插入所有值时工作正常。但我认为 password
字段没有被保存。我正在使用内置的 auth
对象来验证用户登录我的站点。当用户在站点注册并尝试登录时,password
不匹配,用户无法登录。当我从 password
更改 admin
时,我可以成功登录。那么,有人可以帮助我吗?
这是我扩展 UserCreationForm
的方式:
from django import forms
from django.contrib.auth.forms import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.TextInput()
last_name = forms.TextInput()
class Meta:
model = User
fields = ("username", "first_name", "last_name", "email", "password1", "password2")
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
现在,我单击
the form
链接并更改密码。 最佳答案
问题
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
^
|___ super of UserCreationForm is ModelForm!
您的代码正在调用
UserCreationForm
的 super 而不是您自己形式的 super RegistrationForm
。 (UserCreationForm
的super 是ModelForm
不知道如何处理用户注册,比如保存密码)结果是
user.set_password()
没有在任何地方被调用 但是,我会说不需要再次调用
user.set_password
,因为您的 super
已经这样做了。UserCreationForm.save()
定义如下:def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Source code on github
解决方案
你应该有这样的东西
def save(self, commit=True):
# Call save of the super of your own class,
# which is UserCreationForm.save() which calls user.set_password()
user = super(RegistrationForm, self).save(commit=False)
# Add the things your super doesn't do for you
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
关于python - 扩展 UserCreationForm : password not saved,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34849328/