gpt4 book ai didi

python - Flask 使用 jinja2 从列表中迭代 WTForms 中的数据以生成表单字段

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:29 25 4
gpt4 key购买 nike

我正在尝试使用 BooleanField() 从 json 文件在 html 表中生成 list 到目前为止,我没有使用 wtforms:

来自 View .py

from app import app

from flask import render_template

json_data = [{'Description':'Red', 'id':'f1'},{'Description':'Green', 'id':'f2'},{'Description':'Blue', 'id':'f3'}]


@app.route('/taggs', methods = ['GET', 'POST'])
def taggs()
return render_template('taggs.html', jdata = json_data)

来自 taggs.html

<form role="form" method= "post">
<table id='ctable'>
<thead>
<tr>
<th data-field="Description"></th>
<th data-field="Selection"></th>
</tr>
</thead>
<tbody>

</tbody>
{% for i in jdata %}
<tr>
<td>{{ i.Description }}</td>
<td><input type ="checkbox" id = "{{ i.id }}"></td>
</tr>
{% end for%}
</table>
</form>

有没有一种方法可以使用 wtforms 中的列表生成表单字段?或者我是否必须创建一个类并声明列表中的每个变量?

最佳答案

是的,您可以在 View 函数中动态执行此操作。

The docs有一个这样的例子,您可以按照以下方式进行修改:

from flask import render_template, request
from flask_wtf import Form
from wtforms import BooleanField

json_data = [{'Description':'Red', 'id':'f1'},
{'Description':'Green', 'id':'f2'},
{'Description':'Blue', 'id':'f3'}]


@app.route('/taggs', methods = ['GET', 'POST'])
def taggs():
class CustomForm(Form):
pass

for item in json_data:
setattr(CustomForm, item["id"],
BooleanField(item["description"], id=item["id"]))

form = CustomForm(request.form)

return render_template('taggs.html', form=form)

关于python - Flask 使用 jinja2 从列表中迭代 WTForms 中的数据以生成表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com