如何使用 WTForms 从模型列表创建表单?
-
21-12-2019 - |
题
我有一个清单 Prediction
楷模。我想将它们绑定到表单并允许使用回发。我如何构建我的表格,以便帖子将主/客场得分与 Prediction
楷模 id
我绑定到表单的每个项目的字段?
看法
@app.route('/predictor/',methods=['GET','POST'])
@login_required
def predictions():
user_id = g.user.id
prediction= # retrieve prediction
if request.method == 'POST':
if form.validate() == False:
flash('A score is missing, please fill in all predictions')
render_template('predictor.html', prediction=prediction, form=form)
else:
for pred in prediction:
# store my prediction
flash('Prediction added')
return redirect(url_for("predictions"))
# display current predictions
elif request.method == 'GET':
return render_template('predictor.html', prediction=prediction, form=form)
形式
class PredictionForm(WTForm):
id = fields.IntegerField(validators=[validators.required()], widget=HiddenInput())
home_score = fields.TextField(validators=[validators.required()])
away_score = fields.TextField(validators=[validators.required()])
模板
<form action="" method="post">
{{form.hidden_tag()}}
<table>
{% for pred in prediction %}
<tr>
<td>{{pred.id}}</td>
<td>{{form.home_score(size=1)}}</td>
<td>{{form.away_score(size=1)}}</td>
</tr>
{% endfor %}
</table>
<p><input type="submit" value="Submit Predictions"></p>
</form>
我无法正确绑定我的数据 POST
. 。所需的验证器不断失败,因为发布数据丢失了所有 必需的 字段。
解决方案
您需要一个将绑定到预测列表中的项目的子表单:
您所描述的表格仅允许您提交单个预测。似乎存在差异,因为您绑定了可迭代的预测,并且您似乎希望为每个预测都有一个主场和客场预测。事实上,就目前情况而言,它永远不会回发 id
场地。这总是会导致您的表单验证失败。我认为你想要的是子表单列表。就像这样:
# Flask's form inherits from wtforms.ext.SecureForm by default
# this is the WTForm base form.
From wtforms import Form as WTForm
# Never render this form publicly because it won't have a csrf_token
class PredictionForm(WTForm):
id = fields.IntegerField(validators=[validators.required()], widget=HiddenInput())
home_score = fields.TextField(validators=[validators.required()])
away_score = fields.TextField(validators=[validators.required()])
class PredictionListForm(Form):
predictions = FieldList(FormField(PredictionForm))
您的视图需要返回以下内容:
predictions = # get your iterable of predictions from the database
from werkzeug.datastructures import MultiDict
data = {'predictions': predictions}
form = PredictionListForm(data=MultiDict(data))
return render_template('predictor.html', form=form)
您的表单需要更改为类似这样的内容:
<form action='my-action' method='post'>
{{ form.hidden_tag() }}
{{ form.predictions() }}
</form>
现在这将打印一个 <ul>
与 <li>
每个项目,因为这就是 FieldList 的作用。我将由您来设计它的样式并将其转换为表格形式。这可能有点棘手,但并非不可能。
在 POST a 上,您将获得一个表单数据字典,其中包含每个预测的主场和客场得分 id
. 。然后您可以将这些预测绑定回您的 SQL炼金术 模型。
[{'id': 1, 'home': 7, 'away': 2}, {'id': 2, 'home': 3, 'away': 12}]
其他提示
{% for key in di_RAA %}
<tr>
<td><form id="Run" action="{{ url_for('index') }}" method="post">
<input type="submit" class="btn" value="TEST" name="RUN_{{key}}">
</form></td>
</tr>
{% endfor %}
它为多个按钮提供了其他简单的解决方案。FieldList很好,但是很难获取每个按钮的名称和触发功能。
from wtforms import fields
from wtforms.fields import FieldList, FormField
from wtforms import validators
一些提示,它可能会添加一些导入并清除导入错误消息。
不隶属于 StackOverflow