flask-wtf行为,在视图中有2个表单

时间:2014-07-26 13:11:22

标签: python flask flask-wtforms

示例2在一个页面中形成:

<form name="form_A" class="form-inline" action="/" method="post">
{{form_A.hidden_tag()}}
    {{form_A.name(type="text", class="form-control")}}
    <input type="submit" name="form_A" id="form_A" class="btn btn-sm btn-success" value="FORM_A">
</form>

<form name="form_B" class="form-inline" action="/" method="post">
{{form_B.hidden_tag()}}
    {{form_B.name(type="text", class="form-control")}}
    <input type="submit" name="form_A" id="form_A" class="btn btn-sm btn-success" value="FORM_B">
</form>

和路由器:

@app.route('/', methods = ['GET', 'POST'])
def index():
    form_A = ExampleForm1(request.form)
    form_B = ExampleForm1(request.form)
    if form_A.validate_on_submit():
        ...
    if form_B.validate_on_submit():
        ...

任何提交按钮(FORM_A或B)一起调用form_A.validate_on_submit()和form_B.validate_on_submit()(!)。为什么呢?
以及如何在这种情况下只提交一份表格?

编辑:

我解决了这个问题,只需在任何字段中添加检查数据并使用is_submitted方法:

if form_A.is_submittied() and form_A.name.data:
    ...

1 个答案:

答案 0 :(得分:0)

使用多个表单时,需要为每个表单添加前缀:

form_A = ExampleForm1(request.form, prefix='form_a')
form_B = ExampleForm1(request.form, prefix='form_b')