我在django中有以下表格:
class UserEmailRegistrationForm(forms.Form):
password = forms.PasswordField(max_length=32, label=_('Password'),
validators=[validators.validate_password])
email = forms.EmailField(label=_('Email'),
validators=[validators.validate_email])
first_name = forms.CharField(max_length=35, label=_('First name'),
validators=[validators.validate_name])
last_name = forms.CharField(max_length=35, label=_('Last name'),
validators=[validators.validate_name])
大多数验证器都是自定义的,但validate_email
中显示django.core.validators
。此外,这是我的观点的相关部分:
form = UserEmailRegistrationForm(PUT)
# Validate incoming data
if not form.is_valid():
return HttpResponse(form.errors.as_json(),
content_type='application/json', status=422)
所有验证工作正常,但当我传递无效的电子邮件地址时,我Enter a valid email address.
会form.errors
两次。以下是我得到的回复:
{"email": [{"message": "Enter a valid email address.", "code": "invalid"}, {"message": "Enter a valid email address.", "code": "invalid"}]}
可能导致此问题的原因以及如何解决?
答案 0 :(得分:3)
调试/看看发生了什么。在IDE中单击EmailField并按照层次结构...
1.您的代码:
email = forms.EmailField(label=_('Email'),
validators=[validators.validate_email])
2.EmailField:
class EmailField(CharField):
widget = EmailInput
default_validators = [validators.validate_email]
3.CharField /没有什么有趣的。
class CharField(Field): ...
4 Field.__init__(...)
:
...
self.validators = self.default_validators + validators
super(Field, self).__init__()
简而言之,您使用了两次validate_email。
答案 1 :(得分:1)
正如François所暗示的那样,两个相同的验证器与您的email
字段相关联。第一个是默认情况下,然后通过提供validators
关键字参数(validators=[validators.validate_email]
)的值来添加第二个。此验证器列表将附加到任何默认值。因此,您会看到2条验证错误消息。
$ python manage.py shell
>>> from django import forms
>>> from django.core import validators
>>> email = forms.EmailField(label=_('Email'), validators=[validators.validate_email])
>>> email.validators
[<django.core.validators.EmailValidator object at 0x2bc0190>, <django.core.validators.EmailValidator object at 0x2bc0190>]
因此,您可以看到上面有2个注册的验证器。当表单被验证时,两者都被执行:
>>> email.run_validators('abc@abc.com')
>>> email.run_validators('abc')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/mhawke/virtualenvs/django_1.6/lib/python2.7/site-packages/django/forms/fields.py", line 139, in run_validators
raise ValidationError(errors)
ValidationError: [u'Enter a valid email address.', u'Enter a valid email address.']
要修复,只需声明没有验证器的电子邮件字段:
>>> email = forms.EmailField(label=_('Email'))
>>> email.validators
[<django.core.validators.EmailValidator object at 0x2bc0190>]
>>> email.run_validators('abc@abc.com')
>>> email.run_validators('abc')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/mhawke/virtualenvs/django_1.6/lib/python2.7/site-packages/django/forms/fields.py", line 139, in run_validators
raise ValidationError(errors)
ValidationError: [u'Enter a valid email address.']