电子邮件验证(1062,“重复输入''用于密钥'电子邮件'”)

时间:2015-03-31 10:40:27

标签: python django django-models django-forms

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

这是我的表格:

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.")

当我尝试保存模型时,我收到错误消息:

IntegrityError at /registracija/
(1062, "Duplicate entry '' for key 'email'")

如果您还有其他需要,请告诉我

1 个答案:

答案 0 :(得分:1)

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

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