我正在尝试使用.
从json文件生成html表中的清单到目前为止我没有使用wtforms:
来自view.py
BooleanField()
来自taggs.html的
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)
有没有办法使用wtforms中的列表生成表单字段?或者我是否必须创建一个类并在列表中声明每个变量?
答案 0 :(得分:1)
是的,您可以在视图功能中动态执行此操作。
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)