我试图在我的验证中实现一个特殊的技巧 . 我希望程序仅在两个字段都无效时才引发ValidationError . 一个是电子邮件的字段,因此是模型中的emailField . 另一个是电话号码,是模型中的CharField .
models.py
...
email = models.EmailField(max_length=128, blank=True, null=True)
telephone = models.CharField(max_length=32, blank=True, null=True)
...
在forms.py我使用内置的清理电子邮件和构建一个自定义的电话号码 .
forms.py
def clean(self):
cleaned_data=super(ContactInstructorForm, self).clean()
try:
email = self.cleaned_data['email']
except:
email = False
telephone = self.cleaned_data['telephone']
mobile_regex = r'^(\+46|0|\(\+46\)) *(7[0236])( |-|)(\d{4} \d{3}|\d{3} \d{4}|\d{3} \d{2} \d{2}|\d{2} \d{2} \d{3}|\d{7})$'
home_phone_regex = r'^(\+46|0|\(\+46\)) *(8)( |-|)(\d{4} \d{2}|\d{2} \d{4}|\d{3} \d{3}|\d{2} \d{2} \d{2}|\d{6})$'
if not re.match(mobile_regex, telephone) and not re.match(home_phone_regex, telephone):
telephone = False
if not email and not telephone:
raise ValidationError()
但是,问题是内置的clean()方法不仅返回所有已验证字段及其值的字典 . 但失败时也会自动引发ValidationError .
这只会导致我的程序在输入的电子邮件无效时失败(即使电话号码正常) This behaviour is unwanted!
所以最后我想问一下构建电子邮件内置验证的最佳方法(特别是当电话号码有效时),但同时使用内置验证(特别是当电话号码无效时)对于所有其他领域 .
Update: 我也在使用模块"djangospam"中的自动蜜 jar . 这包含在模板中,就在表单之前 .
{% include 'djangospam/form.html' %}
哪个转换为HTML:
<form method="post" action="http://www.somewebsite.com">
<label for="honeypot">Honeypot</label>
<input id="honeypot" type="text" name="honeypot"></input>
<label for="name">Name</label>
<input id="name" type="text" name="name"></input>
<label for="email">E-mail</label>
<input id="email" type="text" name="email"></input>
<label for="url">Website (optional)</label>
<input id="url" type="text" name="url"></input>
<label for="comment">Your comment</label>
<textarea id="comment" name="comment"></textarea>
<input type='hidden' name='csrfmiddlewaretoken' value='8Nwq32Mbh6KA1h3C1U4ZMRe2nTkUGSbebVgsQbF8zZL2dKoZAS4kjoQM8W1NEb3g' />
<input type="submit" value="Send"></input>
</form>
1 回答
您的电子邮件始终使用
email = self.cleaned_data['email']
进行设置,即始终为True
. 它永远不会遇到except块 . 这与最后一个条件相结合,将其设置为Validation error
. 把你的电子邮件正则表达式和你用电话一样,你应该没问题 .编辑: - 像这样的东西