Django更改电子邮件地址确认密码

2024-04-25 07:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

表单确实会更改电子邮件地址,但用户可以输入密码的任何值,电子邮件地址也会更改。在

由于某些原因,在更改电子邮件之前,密码没有被检查和确认。在

我不知道我做了什么。在

这是我的表格代码:

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

这是我的视图.py代码:

^{pr2}$

Tags: selfnewdataifaddressemaildefmail