Allow empty password fields in user model when updating profile in Django

Edited to include code

class UserForm(UserCreationForm): def __init__(self, *arg, **kw): super(UserForm, self).__init__(*arg, **kw) # re-order so email appears last on this form email_field = self.fields.pop('email') self.fields['email'] = email_field class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') 

I have a form where users can update their profile data.

Users can optionally update their passwords , but this is not required to update other profile fields.

The problem is that my checks are performed when the password and password confirmation fields are empty.

The User models password field, which I believe is the required=True and blank=False field, so I just need to ignore the empty input from the forms when checking on this model.

The User model is the one that comes with Django:

from django.contrib.auth.models import User

thanks

+6
source share
2 answers

UserCreationForm is for creating . Better to create a new ModelForm than use this.

 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 UserCreationForm , which I do not recommend. You can do it:

 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 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') 

There is another special form that you can use to change passwords, which is django.contrib.auth.forms.SetPasswordForm , since changing a password is another process of updating user information

+9
source

You can create your own password form field and process it manually. Or you can override the cleanup method and remove the password-related errors yourself.

0
source

All Articles