【问题标题】:WTForms not validating typeWTForms 不验证类型
【发布时间】:2015-04-07 21:34:31
【问题描述】:

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

【问题讨论】:

标签: python wtforms


【解决方案1】:

数据需要传递给表单的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

感谢 cmets 中的 Max 指出此链接以及答案和更多详细信息:WTForms: IntegerField skips coercion on a string value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2019-05-10
    • 2021-08-09
    • 2014-02-05
    相关资源
    最近更新 更多