只能将字符串值粘贴到 Flask WTF-Forms 字段

Only able to paste string values to a Flask WTF-Forms field

我正在尝试让视图函数将十进制值(最终来自数据库)粘贴到 WTF 表单字段中。除非我将该字段更改为字符串字段,否则该值不会显示。我需要一些额外的东西来将数值粘贴到小数字段吗?

我创建了一个小的、希望可重现的示例来仅测试此功能。它有一个字段,在加载页面时,应该在该字段中粘贴一个值。

最初我尝试使用小数字段进行此操作,并尝试粘贴一个随机数,但在呈现页面时该数字并未显示。当字段更改为 IntegerField 或 FloatField

时也会发生同样的情况

将表单字段更改为字符串字段时,该值将在页面呈现时显示 - 但这不是理想的解决方案,因为该值将是一个字符串。

routes.py

from flask import render_template, flash
from app import app
from app.forms import TestForm

@app.route('/',methods=['GET','POST'])
@app.route('/index/',methods=['GET','POST'])
def index():
    # define form
    test_form = TestForm()

    test_form.testfield.data = 10

    return render_template('sandbox_home.html',
        test_form = test_form
        )

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField,DecimalField

class TestForm(FlaskForm):
    testfield=StringField()

sandbox_home.html

<!doctype html>

<title>My Safe Place</title>

<p>I exist to paste values to form fields!</p>

<form action="" method="post" novalidate>  
  {{ test_form.hidden_tag() }}
  {{ test_form.testfield() }}
</form>

如果输入的类型正确,我希望无论字段类型如何,该值都会显示。我猜这是一个数据类型问题,但我不确定问题出在哪里。

这是一个显示此工作正常的最小示例:

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


app = Flask(__name__)
app.secret_key = ";lskjflksdjflsdkjfsd;lghdi9uawhj"


class TestForm(FlaskForm):
    test_str = StringField()
    test_int = IntegerField()
    test_dec = DecimalField()


template = """
<!doctype html>

<title>My Safe Place</title>

<p>I exist to paste values to form fields!</p>

<form action="" method="post" novalidate>
  {{ test_form.hidden_tag() }}
  {{ test_form.test_str() }}
  {{ test_form.test_int() }}
  {{ test_form.test_dec() }}
</form>
"""


if __name__ == "__main__":
    # simulate handling a request
    with app.test_request_context():
        test_form = TestForm()
        test_form.test_str.data = 10
        test_form.test_int.data = 10
        test_form.test_dec.data = 10

        # render the template and save to file so can open in browser
        with open("test.html", "w") as f:
            f.write(render_template_string(template, test_form=test_form))

它将呈现的模板保存到名为 test.html 的文件中,如下所示:

<!doctype html>

<title>My Safe Place</title>

<p>I exist to paste values to form fields!</p>

<form action="" method="post" novalidate>
  <input id="csrf_token" name="csrf_token" type="hidden" value="IjUyMDI2NDYxMDY2OTc3N2E0OTU3ODYwM2M0Y2RiMzNjYjY5OWZlMDAi.XcXs_g.55IiutLhjhC2h7J9MI8rWtNu9co">
  <input id="test_str" name="test_str" type="text" value="10">
  <input id="test_int" name="test_int" type="text" value="10">
  <input id="test_dec" name="test_dec" type="text" value="10.00">
</form>

这是浏览器中的截图:

从呈现的模板中可以看出,WTForms 不区分浏览器中不同类型的字段(即它们都是 type="text")。如果您能让我知道如何修改此脚本以重现您的错误,我很乐意再次查看它。