WTForms不验证类型

时间:2015-04-07 21:34:31

标签: python wtforms

我尝试使用wtforms检查字典中的数据是否属于所需类型。在下面的示例中,我想确保字典中的some_field是整数。该文档让我相信,如果我使用IntegerField,数据将被强制转换为整数,StringField将强制转换为字符串等。但是,foo.validate()正在返回True即使some_field的类型不是整数。这是预期的行为,为什么?如果是预期的行为,是否可以根据需要使用wtforms进行类型验证?

>>> from wtforms import Form, IntegerField, validators

>>> class Foo(Form):
...     some_field = IntegerField(validators=[validators.Required()])

>>> foo = Foo(**{'some_field':'some text input'})

>>> foo.data
{'some_field': 'some text input'}

>>> foo.validate()
True

>>> IntegerField?
Type:            type
String form:     <class 'wtforms.fields.core.IntegerField'>
File:            c:\users\appdata\local\continuum\anaconda\envs\env\lib\site-packages\wtforms\fields\core.py
Init definition: IntegerField(self, label=None, validators=None, **kwargs)
Docstring:
A text field, except all input is coerced to an integer.  Erroneous input
is ignored and will not be accepted as a value.

1 个答案:

答案 0 :(得分:0)

需要将数据传递给表单formdata参数,以强制进行类型强制。要将数据传递到formdata,请使用MultiDict

In [2]: from wtforms import Form, IntegerField, validators

In [3]: class Foo(Form):
   ...:     some_field = IntegerField(validators=[validators.Required()])

In [4]: from werkzeug.datastructures import MultiDict

In [5]: foo = Foo(formdata=MultiDict({'some_field':'some text input'}))

In [6]: foo.data
Out[6]: {'some_field': None}

In [7]: foo.validate()
Out[7]: False

感谢Max在评论中指出了这个链接的答案和更多细节:WTForms: IntegerField skips coercion on a string value

相关问题