gpt4 book ai didi

python - 电子邮件验证(1062, "Duplicate entry ''对于 key 'email'“)

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:51 24 4
gpt4 key购买 nike

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

这是我的表格:

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

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

最佳答案

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

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

关于python - 电子邮件验证(1062, "Duplicate entry ''对于 key 'email'“),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366694/

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