在 django 中的 EmailField 验证中例外
我有一个名为 EmailHistory
的模型,其中一个字段如下所示:
from_email = models.EmailField(verbose_name="From:")
我创建了一个 ModelForm 并希望验证电子邮件地址,除非将其设置为“匿名”。我尝试了以下方法,但没有成功。
class EmailForm(ModelForm):
class Meta:
model = EmailHistory
exclude = ('to_email')
to_emails = forms.CharField()
def clean_from_email(self):
from_email = self.cleaned_data['from_email']
if from_email == "Anonymous":
return from_email
else:
return super(EmailForm, self).clean_from_email();
I have model called EmailHistory
with one of the fields that look like this:
from_email = models.EmailField(verbose_name="From:")
I created a ModelForm and want to validate for email addresses unless it's set to "Anonymous". I tried the following, to no avail.
class EmailForm(ModelForm):
class Meta:
model = EmailHistory
exclude = ('to_email')
to_emails = forms.CharField()
def clean_from_email(self):
from_email = self.cleaned_data['from_email']
if from_email == "Anonymous":
return from_email
else:
return super(EmailForm, self).clean_from_email();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑问题在于,正如 文档 所解释的那样, <底层表单字段的 code>clean 方法(依次运行验证器)在表单本身的特定
clean_form_field
方法之前运行。您可能希望在表单中使用普通的 CharField,并自行将电子邮件验证添加到 clean 方法中。I suspect the issue is that, as the documentation explains, the
clean
method of the underlying form field - which in turn runs the validators - is run before the specificclean_form_field
method in the form itself. You'll probably want to use a normal CharField in your form, and add the email validation into the clean method yourself.如果不重新定义
from_email
,我就无法让它工作。因此,我重新定义了它,然后使用 django.core.validators.validate_email 进行了电子邮件验证:I couldn't get it to work without redefining
from_email
. So, I redefined it and then did an email validation usingdjango.core.validators.validate_email
: