电子邮件验证(1062,“密钥‘email’的重复条目’”)

2024-10-06 14:26:43 发布

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

我在注册中有两个电子邮件字段来验证电子邮件是否正确:

这是我的表格:

class RegistrationForm(forms.ModelForm):
    email1 = forms.EmailField(label="El.paštas")
    email2 = forms.EmailField(label="Pakartokite el. paštą")

    class Meta:
        model = AuthUser
        fields = ("email1", "email2", "first_name", "last_name", "password", "city", "other_city", "age", "accepts_emails")
        widgets = {
            "password": forms.PasswordInput(),
        }

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields["city"].queryset = City.objects.filter(other_city=False)

        for field_name in self.fields:
            field = self.fields.get(field_name)

            if field and field_name != "accepts_emails" and field_name != "other_city":
                field.widget.attrs.update({"class": "form-control"})

    def clean_email2(self):
        email1 = self.cleaned_data["email1"]
        email2 = self.cleaned_data["email2"]

        if email1 and email2 and email1 != email2:
            raise forms.ValidationError("El. pašto adresai nesutampa.")

        try:
            AuthUser._default_manager.get(email=email1)
        except AuthUser.DoesNotExist:
            return email1

        raise forms.ValidationError("Toks el. paštas jau naudojamas.")

当我试图保存我的模型时,我得到一个错误消息:

^{pr2}$

如果你还需要什么,请告诉我


Tags: andnameselfcityfieldfields电子邮件forms
1条回答
网友
1楼 · 发布于 2024-10-06 14:26:43

您应该重写save()方法并在那里设置用户的email字段:

def save(self, *args, **kwargs):
    user = super(RegistrationForm, self).save(commit=False)
    user.email = self.cleaned_data['email1']
    user.save()
    return user

相关问题 更多 >