Flask 使用 jinja2 从列表中迭代 WTForms 中的数据以生成表单字段
Flask Iterating data in WTForms from a list with jinja2 to generate form fields
我正在尝试使用 BooleanField()
从 json 文件在 html table 中生成清单 目前为止我没有使用 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 中的列表生成表单字段?还是我必须创建一个 class 并声明列表中的每个变量?
是的,您可以在视图函数中动态执行此操作。
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)
我正在尝试使用 BooleanField()
从 json 文件在 html table 中生成清单 目前为止我没有使用 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 中的列表生成表单字段?还是我必须创建一个 class 并声明列表中的每个变量?
是的,您可以在视图函数中动态执行此操作。
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)