Allow blank password fields on User model when updating profile in Django

后端 未结 2 572
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 00:34

Edited to include code

class UserForm(UserCreationForm):

    def __init__(self, *arg, **kw):
        super(UserForm, self).__init__(*arg, **kw)

        # re-         


        
2条回答
  •  梦谈多话
    2021-02-06 00:54

    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

提交回复
热议问题