有人可以解释如何验证Django中的电子邮件地址吗? 因此,对于示例,我想检查电子邮件是否是有效的大学电子邮件地址,结尾为.edu。 我怎样才能做到这一点?
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['full_name','email']
def clean_email(self):
email = self.cleaned_data.get('email')
return email
答案 0 :(得分:4)
假设您的SignUp.email
字段是EmailField
,Django将负责验证它是否是有效的电子邮件地址。您需要做的就是检查它是否以.edu
结尾,如果没有,则提出ValidationError
。
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['full_name','email']
def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('.edu'):
raise forms.ValidationError("Only .edu email addresses allowed")
return email
如果创建验证器并将其添加到模型字段可能更好。这样,Django将在您使用SignUpForm
时运行验证程序,并在其他地方(如Django管理员)进行模型验证时运行验证程序。
from django.core.exceptions import ValidationError
def validate_edu_email_address(value):
if email.endswith('.edu'):
raise forms.ValidationError("Only .edu email addresses allowed")
class SignUp(models.Model):
email = models.EmailField(validators=[validate_edu_email_address])
...
答案 1 :(得分:0)
只需为您的需求创建一个正则表达式,或者甚至更好地使用一些标准表达式。
import re
EMAIL_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
# EMAIL_REGEX = r'\w+@\.edu' # If you only want to allow edu.
class SignUpForm(forms.ModelForm):
...
def clean_email(self):
email = self.cleaned_data.get('email')
if email and not re.match(EMAIL_REGEX, email):
raise forms.ValidationError('Invalid email format')
return email
事实上,更好的方法是使用@ {Alasdair建议的EmailField
,这将自动为您确保相同(除非您确实需要将电子邮件地址限制为自定义格式)。