扩展UserCreationForm:密码未保存

时间:2016-01-18 07:31:44

标签: python django

我已成功创建并扩展play.Play.application()以获取UserCreationFormemail& first_name。它可以很好地插入所有值。但我认为last_name字段没有被保存。我使用内置的password对象来验证用户登录我的网站。当在网站中使用注册并尝试登录auth没有匹配且用户无法登录时。当我从password更改password时,我可以成功登录。那么,任何人都可以帮助我吗? 这就是我扩展admin

的方式
UserCreationForm

How I change my password usgin admin?   现在,我点击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 链接,然后更改密码。

1 个答案:

答案 0 :(得分:5)

问题

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
                 ^
                 |___ super of UserCreationForm is ModelForm!

您的代码正在调用UserCreationForm的超级代码,而不是您自己的超级代码RegistrationForm。 (UserCreationForm的超级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