如何使用WTForms从模型列表创建表单?

Lor*_*bat 3 python jinja2 flask wtforms flask-wtforms

我有一个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)
Run Code Online (Sandbox Code Playgroud)

形成

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()])
Run Code Online (Sandbox Code Playgroud)

模板

  <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>
Run Code Online (Sandbox Code Playgroud)

我无法正确绑定我的数据POST.所需的验证器不断失败,因为帖子数据缺少所有必填字段.

nsf*_*n55 6

您需要一个子表单,该子表单将绑定到预测列表中的项目:

您描述的表单只允许您提交单个预测.似乎存在差异,因为您绑定了一个可迭代的预测,并且看起来您想要对每个预测进行回家预测.事实上,它永远不会发回一个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))
Run Code Online (Sandbox Code Playgroud)

您的视图需要返回以下内容:

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)
Run Code Online (Sandbox Code Playgroud)

您的表单需要更改为更像这样的内容:

<form action='my-action' method='post'>
    {{ form.hidden_tag() }}
    {{ form.predictions() }}
</form>
Run Code Online (Sandbox Code Playgroud)

现在这将打印一个<ul>带有<li>每个项目,因为这是FieldList的功能.我会把它放在你的风格上,然后把它变成表格形式.这可能有点棘手,但并非不可能.

在POST a上,您将获得一个formdata字典,其中包含每个预测的主页和客场分数id.然后,您可以将这些预测绑定回SQLAlchemy模型.

[{'id': 1, 'home': 7, 'away': 2}, {'id': 2, 'home': 3, 'away': 12}]
Run Code Online (Sandbox Code Playgroud)