我有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上,您将获得一个formdata词典,其中包含每个预测的得失分id
。然后,您可以将这些预测重新绑定到SQLAlchemy模型中。
[{'id': 1, 'home': 7, 'away': 2}, {'id': 2, 'home': 3, 'away': 12}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句