9

给定一个电子邮件地址(例如: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

使用此代码,我收到错误“'type' object has no attribute ' getitem '”,它可以追溯到我的代码中的“raise forms.ValidationError[...]”行。

谁能看到我做错了什么?谢谢您的帮助!

4

2 回答 2

7

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

raise forms.ValidationError("Please enter a valid Penn Email Address")
于 2012-08-13T18:22:41.083 回答
4

我觉得线...

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

应该

raise forms.ValidationError("Please enter an Email Address with a valid domain")
于 2012-08-13T18:23:09.407 回答