Flask WTForm从字段标签列表



我正在尝试使用Flask, WTForms和Jinja2从给定的标签列表中创建一个动态表单。对于每个给定的标签,表单应该包含一个StringField。我目前的方法是使用FieldList,如下面的代码所示。

这种方法的问题是,我无法区分每个请求的字典中的键。

request.form给我这个ImmutableMultiDict([('text', ''), ('text', ''), ('submit', 'submit')])和键重复。

如何知道哪个StringField中输入了哪个值?

理想情况下,request.form应该看起来像ImmutableMultiDict([('field 1', ''), ('field 2', ''), ('submit', 'submit')])

前端(index.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="" method="post">
{% for entry in form.entries %}
<p>{{entry.text.label}}: {{ entry.text }}</p> 
{% endfor %}
<p>{{form.submit()}}</p>
</form>
</body>
</html>

后端
from wtforms import FieldList, FormField, StringField, SubmitField
from flask_wtf import FlaskForm

class TextForm(FlaskForm):
text = StringField('Placeholder')
class TextListForm(FlaskForm):
entries = FieldList(FormField(TextForm))
submit = SubmitField(u'submit')

from flask import Flask, render_template, request
app = Flask(__name__)
app.config.update(
SECRET_KEY = 'asdf',
)
field_names = ["field 1", "field 2"]

@app.route('/', methods=['POST', 'GET'])
def index():
fields = []
for name in field_names:
text_entry = TextForm()
text_entry.text.label = name
fields.append(text_entry)
form = TextListForm()
form.entries = fields
if form.is_submitted():
print(request.form)
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)

输出:ImmutableMultiDict([('text', ''), ('text', ''), ('submit', 'submit')])

我只是忘了设置字段名:text_entry.text.name = name

@app.route('/', methods=['POST', 'GET'])
def index():
fields = []
for name in field_names:
text_entry = TextForm()
text_entry.text.label = name
text_entry.text.name = name
fields.append(text_entry)
form = TextListForm()
form.entries = fields
if form.is_submitted():
print(request.form)
return render_template('index.html', form=form)
现在返回所需的字典:ImmutableMultiDict([('field 1', ''), ('field 2', ''), ('submit', 'submit')])

相关内容

  • 没有找到相关文章

最新更新