如何在表格中验证电子邮件地址的域名?

2024-05-22 00:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

提供电子邮件地址(例如:goelv@example.com),如何验证域(“example.com网站“”包含在域列表中。如果域(“example.com网站“)不在指定的列表中,窗体应引发某种类型的错误。在

这就是我目前所做的表单.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

通过这段代码,我得到错误“'type'object has no attribute'getitem”,它可以追溯到“raise”行forms.ValidationError表格.ValidationError[…]”在我的代码里。在

谁能看出我做错了什么吗?谢谢你的帮助!在


Tags: selfcom列表data网站exampleemaildomain
2条回答

我想这条线。。。在

raise forms.ValidationError["Please enter an Email Address with a valid domain"]

应该是

^{pr2}$

您需要在raise行中使用()而不是{},如下所示:

raise forms.ValidationError("Please enter a valid Penn Email Address")

相关问题 更多 >