IntegerField 不验证空字符串

qxu*_*u21 3 wtforms flask-wtforms

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

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)
Run Code Online (Sandbox Code Playgroud)

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

virtualenv flask
source flask/bin/activate
pip install flask flask-wtf
export FLASK_APP=app.py
python3 app.py
Run Code Online (Sandbox Code Playgroud)

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

我想让我的 IntegerField 为空。我认为解决方案是继承IntegerField 并覆盖 pre_validate() 或 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
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 子类化和覆盖正确的解决方案?
  • 如果是这样,我是否覆盖 pre_validate()、post_validate() 或两者,以及如何覆盖?我需要return True在他们里面吗?

sna*_*erb 6

The Optional validator allows empty entries on form fields.

>>> 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
Run Code Online (Sandbox Code Playgroud)

From the 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.