如何进行用户名和电子邮件字段验证

时间:2019-07-06 04:57:38

标签: django

我正在尝试在注册过程中检查数据库中是否已经存在电子邮件,但是使用以下代码,我没有收到电子邮件

forms.py

from django.forms import ModelForm
from django import forms
from . models import registration_form

class signup_form(ModelForm):
    Password = forms.CharField(widget=forms.PasswordInput())
    Confirm_pwd = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = registration_form
        fields=['Firstname','Lastname','Username','Email','Password','Confirm_pwd']
    def clean(self):
        cleaned_data = super(signup_form, self).clean()
        password = cleaned_data.get("Password")
        confirm_password = cleaned_data.get("Confirm_pwd")
        print(confirm_password)

        if password != confirm_password:
            print("yes")
            raise forms.ValidationError(
                "password and confirm_password does not match"
                )   

    def clean_Email(self):
        Email = self.cleaned_data.get('Email')
        try:
          match = registration_form.objects.get(Email=Email)
          print(match)
        except registration_form.DoesNotExist:
        # Unable to find a user, this is fine
          return Email
        raise forms.ValidationError('This email address is already in use.')    

它抛出一个错误,
MultipleObjectsReturned at /form/ get() returned more than one registration_form -- it returned 10

有人可以帮助我实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

registration_form字段上,您的unique=True模型似乎未设置为Email,并且您的数据集包含一个以上具有提供值的registration_form对象。您将需要处理MultipleObjectsReturned。 另一个建议是在不区分大小写的情况下执行过滤器:

match = registration_form.objects.get(Email__iexact=Email)

最终,您可以通过迁移处理重复的条目,在处理registration_form.Email异常的同时,创建unique=True字段.get并执行MultipleObjectsReturned

def clean_Email(self):
    Email = self.cleaned_data.get('Email')
    try:
      match = registration_form.objects.get(Email__iexact=Email)
      print(match)
    except registration_form.DoesNotExist:
      # Unable to find a user, this is fine
      return Email
    except registration_form.MultipleObjectsReturned:
      # Pass here to hit the validation error
      pass
    raise forms.ValidationError('This email address is already in use.')

您只需调整查询以检查:registration_form.objects.filter(Email__iexact=Email).exists()

def clean_Email(self):
    Email = self.cleaned_data.get('Email')
    match = registration_form.objects.filter(Email__iexact=Email).exists()

    if match:
        raise forms.ValidationError('This email address is already in use.')
    return Email