在仅接受Yahoo,Gmail和Outlook的电子邮件中引发验证错误

时间:2019-04-19 03:13:28

标签: django

我在电子邮件字段中提出了自定义验证错误,该错误仅接受yahoo,gmail和Outlook。我在这里做什么错了?

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile, Testimonial

class UserUpdateForm(forms.ModelForm):
  username = forms.CharField()
  first_name = forms.CharField()
  last_name = forms.CharField()
  email = forms.EmailField()

  class Meta:
    model = User
    fields = ['username', 'email', 'first_name', 'last_name']

  def clean_email(self):
    email = self.cleaned_data.get('email')
    email_exists = User.objects.filter(email=email) 
    accepted_domains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com'] 
    username = self.cleaned_data.get('username')  
    _, domain = email.split('@')
    if email_exists.exists():     
      raise forms.ValidationError("Email is taken") 
    elif domain.lower() not in accepted_domains:      
      raise forms.ValidationError("Invalid email")
    return email   

1 个答案:

答案 0 :(得分:1)

您可以这样做:

accepted_domains = ['gmail.com', 'yahoo.com', 'outlook.com']

_, domain = email.split('@')
if email_exists.exists() and not self.instance and self.instance.pk==None:
  raise forms.ValidationError("Email is taken") 
if domain.lower() not in accepted_domains:
  raise forms.ValidationError("Email should be gmail, yahoo and outlook only")
return email