class UserForm(UserCreationForm):
def __init__(self, *arg, **kw):
super(UserForm, self).__init__(*arg, **kw)
# re-
UserCreationForm
is intended to be used for creation. It's better to create a new ModelForm than using this one.
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
Or if you want to subclass the UserCreationForm
which I doesn't recommend. You can do this :
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
I recommend you to use a simple
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')
For passwords changing there's another dedicated form that your can use which is django.contrib.auth.forms.SetPasswordForm
since changing the password is a different process from updating user informations
You can create your own password form field and handle it manually. Or you can override clean method and remove password related errors yourself.