我在注册时有两个电子邮件字段来验证电子邮件是否正确:
这是我的表格:
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'")
如果您还有其他需要,请告诉我
答案 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