wtforms - IntegerField 不验证空字符串

标签 wtforms flask-wtforms

我发现 IntegerField 在为空时不验证。要重现,请复制以下 block :

from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import IntegerField

app = Flask(__name__)
app.config['WTF_CSRF_ENABLED'] = False

class DemoForm(FlaskForm):
    demofield = IntegerField('demofield')

@app.route('/', methods=("GET","POST"))
def index():
    form = DemoForm()
    if form.validate_on_submit():
        return ("The form validated!")
    return render_template_string("<!DOCTYPE HTML> This is my form! <form method=\"post\">{% for field in form %}{{field}}{% endfor %}<input type=\"submit\">", form=form)

app.run(debug=True)

并将其作为 app.py 保存在自己的目录中。然后打开一个终端,cd 到目录,然后运行以下命令:

virtualenv flask
source flask/bin/activate
pip install flask flask-wtf
export FLASK_APP=app.py
python3 app.py

在网络浏览器中连接到 localhost:5000。在表单字段中输入一个整数并提交将显示“表单已验证!”在字段中输入非整数的内容,或将字段留空,然后提交只会重新加载页面。这确实有一定道理,因为不能将 ""强制转换为整数。

我想让我的 IntegerField 为空。我认为解决方案是继承 IntegerField 和 override pre_validate() or post_validate() .我有:

class OptionalIntegerField(IntegerField):
    def post_validate(self, form, validation_stopped):
        print("post_validate is being called")
        if (self.data in (None, "")):
            return True

我的问题是:

  • 子类化和覆盖是正确的解决方案吗?
  • 如果是这样,我是否覆盖 pre_validate()、post_validate() 或两者,如何覆盖?我是否需要在其中返回 True

最佳答案

Optional 验证器允许在表单字段上输入空值。

>>> from webob.multidict import MultiDict

>>> class F(Form):
...     foo = IntegerField(validators=[validators.Optional()])

>>> f = F(formdata=MultiDict(foo=1))
>>> f.validate()
True
>>> f = F(formdata=MultiDict(foo=''))
>>> f.validate()
True
>>> f = F(formdata=MultiDict(foo='a'))
>>> f.validate()
False

来自docs :

class wtforms.validators.Optional(strip_whitespace=True)

Allows empty input and stops the validation chain from continuing.

If input is empty, also removes prior errors (such as processing errors) from the field.

关于wtforms - IntegerField 不验证空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761931/

相关文章:

jquery - 通过 wtform 字段获取数据迭代

python - Flask with Jinja 在第一页之后出现分页问题

python - Flask SQLAlchemy 中的表单删除方法不起作用

flask - Flask/WTForms 中的动态表单(Formsets)?

python - Flask WTF-forms 添加选择和文本区域

python - 如何创建 WTForms 字段子类?

python - 如何在没有 Flask-WTF 的情况下使用 recaptcha

go - 相当于 Go 的 WTForms?

python - 我无法导入 Flask-WTF TextField 和 BooleanField

python-3.x - 选择 jinja 内的 Flask wtforms selectfield 的默认值以获取动态数据