【发布时间】:2014-07-23 23:50:16
【问题描述】:
我有一个Prediction 模型列表。我想将它们绑定到一个表单并允许使用回发。如何构建我的表单,以便帖子将 Home/Away 分数与我绑定到表单的每个项目的 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 上正确绑定。所需的验证器不断失败,因为发布数据缺少所有 必填 字段。
【问题讨论】:
-
没问题。我真的不能再帮你了。这是一个工作要点gist.github.com/nsfyn55/039288a4c1a6dd6ca8ee。要么是您未包含某些内容,要么是印刷错误。
-
我刚刚复制了你写的代码,我得到了
-
也许我更新了要点供您比较
-
您是在运行我的要点
python predictions.py还是尝试将其集成到您的代码中。因为这就是我对你的理解,可能有一些印刷错误或其他不相关的问题。 -
我刚刚复制了你的代码并在我的文本编辑器中运行它..sublime text2
标签: python flask jinja2 wtforms flask-wtforms