我有一个用户名表单字段如下:
username = forms.RegexField(regex=r'^[\w]+$', max_length=15,
widget=forms.TextInput(attrs={'placeholder': _('Username')}),
label=_('Username'),
error_message={'invalid':unicode(_('The given username may only contain letters, numbers and underscores.'))},
help_text=_('May only contain the charchters A-Z, a-z and _ max 15 characters.'))
当字段无效时,浏览器中呈现的错误如下:
{'invalid': u'`The given username may only contain letters, numbers and underscores.`'}
这是一个脆弱形式的问题,还是需要采取额外步骤才能简单回归:
The given username may only contain letters, numbers and underscores.
修改
此错误与脆弱表单无关。基本上我试图返回错误的值,但返回错误列表,并包括有关错误类型的信息。当我在shell中运行字段时,我得到相同的值。
答案 0 :(得分:0)
以下是我解决这个问题的方法。
from django.core.validators import RegexValidator
username = forms.CharField( max_length=15,
widget=forms.TextInput(attrs={'placeholder': _('Username')}),
label=_('Username'),
help_text=_('May only contain the charcters A-Z, a-z and _ max 15 characters.'),
validators=[
RegexValidator(
regex=r'^[\w]+$',
message=_('The given username may only contain letters, numbers and underscores.'),
code='invalid'),
]
)
如果您打开shell并测试返回的错误,则复制我遇到的问题,如下所示。
>>> from django import forms
>>> username = forms.RegexField(regex=r'^[\w]+$', error_message={'invalid': 'Does not meet requirement'})
>>> username.clean('foo.bar')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/EJey/Documents/virtualenvs/mysocialenv/lib/python2.7/site-packages/django/forms/fields.py", line 150, in clean
self.run_validators(value)
File "/Users/EJey/Documents/virtualenvs/mysocialenv/lib/python2.7/site-packages/django/forms/fields.py", line 139, in run_validators
raise ValidationError(errors)
ValidationError: [u"{'invalid': 'Does not meet requirement'}"]
或者使用:
error_messages
而不是:
error_message