UserCreationForm
旨在用于创作。创建一个新的 ModelForm 比使用这个更好。
class UserUpdateForm(forms.ModelForm):
# Feel free to add the password validation field as on UserCreationForm
password = forms.CharField(required=False, widget=forms.PasswordInput)
class Meta:
model = User
# Add all the fields you want a user to change
fields = ('first_name', 'last_name', 'username', 'email', 'password')
def save(self, commit=True):
user = super(UserUpdateForm, self).save(commit=False)
password = self.cleaned_data["password"]
if password:
user.set_password(password)
if commit:
user.save()
return user
或者,如果您想继承UserCreationForm
我不推荐的子类。你可以这样做 :
class UserForm(UserCreationForm):
password1 = forms.CharField(label=_("Password"), required=False
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput, required=False)
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email')
def save(self, commit=True):
user = super(UserUpdateForm, self).save(commit=False)
password = self.cleaned_data["password"]
if password:
user.set_password(password)
if commit:
user.save()
return user
我建议你使用一个简单的
class UserUpdateForm(forms.ModelForm):
class Meta:
model = User
# Add all the fields you want a user to change
fields = ('first_name', 'last_name', 'username', 'email')
对于密码更改,您可以使用另一种专用表单,django.contrib.auth.forms.SetPasswordForm
因为更改密码与更新用户信息的过程不同