goe*_*elv 7 python django validation django-forms django-validation
给定一个电子邮件地址(例如:goelv@example.com),如何验证域("example.com")是否包含在给定的域列表中.如果域("example.com")不在指定的列表中,则表单应该引发某种错误.
这就是我目前在forms.py中所拥有的
class UserCreationFormExtended(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2",)
def clean_email(self):
data = self.cleaned_data['email']
domain = data.split('@')[1]
domain_list = ["gmail.com", "yahoo.com", "hotmail.com",]
if domain not in domain_list:
raise forms.ValidationError["Please enter an Email Address with a valid domain"]
return data
def save(self, commit=True):
user = super(UserCreationFormExtended, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
Run Code Online (Sandbox Code Playgroud)
使用此代码,我得到错误"'type'对象没有属性' getitem '",它跟踪我的代码中的"raise forms.ValidationError [...]"行.
谁能看到我做错了什么?谢谢您的帮助!
您需要使用()
而不是[]
在您的raise
行中,如下所示:
raise forms.ValidationError("Please enter a valid Penn Email Address")
Run Code Online (Sandbox Code Playgroud)