我试图使用wtforms来检查字典中的数据是否符合所需的类型。在下面的示例中,我希望确保字典中的some_field是一个整数。文档让我相信,如果我使用IntegerField,数据将被强制为整数,StringField将强制字符串,等等。然而,即使some_field的类型不是整数,foo.validate()仍然返回True。这是预期的行为吗?为什么?如果是预期的行为,是否可以使用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.发布于 2015-04-08 13:12:04
数据需要传递给表单的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
https://stackoverflow.com/questions/29501741
复制相似问题