首页 > 解决方案 > 如何使用旧密码为更新配置文件创建密码确认?

问题描述

我想创建一个更新配置文件的确认。例如,当用户想要更改名称或密码时,他/她应该输入他们的旧密码以进行确认。我怎样才能做到这一点?

模型.py

class UserProfile(AbstractUser, UserMixin):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    password = models.CharField(max_length=250)
    email = models.EmailField(max_length=254)
    image = models.ImageField(upload_to='profile_image', blank=True, null=True, default='profile.png')
 

视图.py

def update_user(request, id):
    user = request.user
    form = SignUpChangeForm(request.POST or None, request.FILES or None, instance=user)
    if form.is_valid():
        form.save()
        ...

        if form.cleaned_data['password1'] != "":
            user.set_password(form.cleaned_data['password1'])
            user.save()
            auth_login(request, user)

        return redirect('home')

    context = {
        'form': form,
    }

    return render(request, "update_user.html", context)

表格.py

class SignUpChangeForm(forms.ModelForm):
    password1 = forms.CharField(max_length=250, required=False,
                                label="New Password (leave blank if you do not want to change it)",
                                widget=forms.PasswordInput)
    password2 = forms.CharField(max_length=250, required=False,
                                label="New Password Confirmation (leave blank if you do not want to change it)",
                                widget=forms.PasswordInput)

    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'email', 'image')
        widgets = {
            'password1': forms.PasswordInput(),
            'password2': forms.PasswordInput(),
            'old_password': forms.PasswordInput(),
        }

    def clean(self):
        cleaned_data = super(SignUpChangeForm, self).clean()
        if cleaned_data['password1'] != cleaned_data['password2']:
            raise ValidationError("Password confirmation does not match!")
        return cleaned_data
  

标签: pythondjango

解决方案


推荐阅读