首页 > 解决方案 > Flask WTForms - 我可以在 routes.py 中定义字段的占位符而不是渲染的模板吗?

问题描述

我目前有一个可行的解决方案,用于制作和填充类似于我的代码中的以下片段的表单:

表格.py

class TestPointForm(FlaskForm):
    injection_value = FloatField('Injection Value', render_kw={'class': 'form-control'})

路线.py

testpoint = TestPoint.query.first()
form = TestPointForm()
return render_template('testpoint.html', form=form, testpoint=testpoint)

测试点.html

<div class="input-group">
    {% if testpoint.injection_value == None %}
    {{ form.injection_value(placeholder=testpoint.placeholder, value="") }}
    {% else %}
    {{ form.injection_value(placeholder=testpoint.placeholder, value=testpoint.injection_value) }}
    {% endif %}
</div>

我有很多这样的字段,我想通过将表单字段的一些预填充移动到我的 routes.py 文件中来清理我的模板文件。我已经能够在我的一些字段中预填充值,form.injection_value.data但我无法预填充诸如占位符或 data_value1 类型字段之类的内容。我还尝试pass在我的末尾添加一个TestPointForm以允许我添加一些其他动态字段,但它不适用于我在这里尝试的内容。

我在 routes.py 文件中尝试了一些不成功的方法,例如:

form.injection_value.render_kw({'placeholder': testpoint.placeholder}) form.injection_value(placeholder=testpoint.placeholder)

我要求的可能吗?在最坏的情况下,我可以坚持使用模板文件中填充的所有 if 语句和字段,但如果可以的话,我真的很想避免它。

标签: pythonflaskjinja2placeholderwtforms

解决方案


推荐阅读