gpt4 book ai didi

python - django更改电子邮件地址-确认密码

转载 作者:行者123 更新时间:2023-12-01 04:52:29 24 4
gpt4 key购买 nike

我有一个允许用户更改其电子邮件地址的表单。该表单还提示用户输入当前密码作为表单的一部分。

表单确实更改了电子邮件地址,但用户可以输入任何密码值,并且电子邮件地址会发生更改。

由于某种原因,在更改电子邮件之前未检查和确认密码。

我不知道自己做了什么。

这是我的表单代码:

class EmailChangeForm(forms.Form):
error_messages = {
'email_mismatch': _("The two e-mail address fields do not match."),
'email_inuse': _("This e-mail address cannot be used. Please select a different e-mail address."),
'password_incorrect': _("Incorrect password."),
}

current_password = forms.CharField(
label=_("Current Password"),
widget=forms.PasswordInput,
required=True
)

new_email1 = forms.EmailField(
label=_("New E-mail Address"),
max_length=254,
required=True
)

new_email2 = forms.EmailField(
label=_("Confirm New E-mail Address"),
max_length=254,
required=True
)

def __init__(self, user, *args, **kwargs):
self.user = user
super(EmailChangeForm, self).__init__(*args, **kwargs)

def clean_current_password(self):
"""
Validates that the password field is correct.
"""
current_password = self.cleaned_data["current_password"]
if not self.user.check_password(current_password):
raise forms.ValidationError(self.error_messages['password_incorrect'], code='password_incorrect',)
return current_password

def clean_new_email1(self):
"""
Prevents an e-mail address that is already registered from being registered by a different user.
"""
email1 = self.cleaned_data.get('new_email1')
if User.objects.filter(email=email1).count() > 0:
raise forms.ValidationError(self.error_messages['email_inuse'], code='email_inuse',)
return email1

def clean_new_email2(self):
"""
Validates that the confirm e-mail address's match.
"""
email1 = self.cleaned_data.get('new_email1')
email2 = self.cleaned_data.get('new_email2')
if email1 and email2:
if email1 != email2:
raise forms.ValidationError(self.error_messages['email_mismatch'], code='email_mismatch',)
return email2

def save(self, commit=True):
self.user.email = self.cleaned_data['new_email1']
if commit:
self.user.save()
return self.user

这是我的views.py代码:

@login_required
def email_change(request):
language_versions = get_language_versions(user=request.user)
if request.method == 'GET':
form = EmailChangeForm(user=request.user)
elif request.method == 'POST':
form = EmailChangeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
messages.success(request, _('successfully updated.'))
return redirect('email_change')
return render(request, 'user_settings/email_change.html', {
'display_default_language': display_default_language(request.user),
'form': form,
'languages': LANGUAGES,
'language_versions': language_versions,
'language_versions_num': len(language_versions),
})

最佳答案

您的clean_password()方法应该被称为clean_current_password()

关于python - django更改电子邮件地址-确认密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com