首页 > 解决方案 > 在仅接受 yahoo、gmail 和 Outlook 的电子邮件中引发验证错误

问题描述

我在仅接受 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   

标签: django

解决方案


你可以这样做:

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

推荐阅读