django - 在仅接受 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
解决方案
你可以这样做:
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
推荐阅读
- django - 在 Django + Elastic Beanstalk 中将 EC2 公共 IP 添加到 ALLOWED_HOSTS 是否安全?
- python - 当条件运行时间太长时,pyspark multiple
- java - 在“connectGatt”之后不会调用蓝牙 LE“onConnectionStateChange”
- c - base-2:为什么 DECIMAL_DIG - DIG == 2 或 3?
- javascript - React Native tabnavigation 在单独的组件中?
- python - 两个 python 类如何声明相互引用和自身引用?
- reactjs - 从 GTM 脚本中减少未使用的 JavaScript
- android - 在 Android 中调用 tflite 模型的问题
- javascript - 如何在没有嵌套订阅的情况下使用 rxjs 处理内部订阅数组
- javascript - 如何将材料表中的数组值在一列中导出到 Excel?