简体   繁体   中英

how use UpdateView change user password in the django

i have something code
1.When I try to change the user password, the password stored in the database is plain text.
2. The database password is empty when the form is submitted without entering a password.

What should I do? thanks

class UserUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = User
template_name = 'users/UserUpdate.html'
context_object_name = 'UserUpdate'
form_class = UserUpdateForm
success_url = reverse_lazy('UserList')
success_message = 'update success'

def form_valid(self, form):
    password = form.cleaned_data.get('password')
    if not password:
        return super().form_valid(form)


    return super().form_valid(form)

forms

class UserUpdateForm(ModelForm):

password = forms.CharField(
    required=False, label="password",
    max_length=32, strip=False,
    widget=forms.PasswordInput,
)

class Meta:

    model = User
    fields = ['username', 'password', 'last_name', 'email', 'is_superuser', 'is_active']


    def save(self, commit=True):
        password = self.cleaned_data.get('password')
        user = super().save(commit=commit)
        if password:
            user.reset_password(password)
        else:
            pass
        return user

There is an example here: https://docs.djangoproject.com/en/2.1/topics/auth/default/#changing-passwords

If you want the code you posted to work, you can use set_password() on the User.

user.set_password('new password')
user.save()

But, as Timmy O'Mahony said, it's better to use https://docs.djangoproject.com/en/2.1/topics/auth/default/#module-django.contrib.auth.forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM