【问题标题】:wtforms submitting wrong formwtforms 提交错误的表单
【发布时间】:2020-06-01 15:56:10
【问题描述】:

我正在 Flask 中制作一个网络应用程序,在一个页面上我有几个表单,当我单击一个表单(称为“UsedBatch”的那个)的提交按钮时,它最终会提交它,就好像它是另一种形式(称为“NewBatch”的形式),我不明白为什么。表单定义如下:

class NewBatch(FlaskForm):
    quantity = IntegerField('Number of items:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    submit = SubmitField('Submit')

class UsedBatch(FlaskForm):
    quantity = IntegerField('Number of items used:', validators=[DataRequired()])
    date = DateField('Date:', default = date.today(), validators=[DataRequired()])
    used_by = StringField('Used by:')
    submit = SubmitField('Submit')

在它们通过模板运行之前,添加表单的一些属性,然后定义它们,如下所示:

for items in items_list:
    setattr(NewBatch, 'item_no', IntegerField(default = items.item_no))
    setattr(UsedBatch, 'item_no', IntegerField(default = items.item_no))
    processed_items_list.append({'item_no':items.item_no, 'quantity':items.quantity, 'items':items.items, 'batch_form':NewBatch(), 'used_form':UsedBatch()})
used_form = UsedBatch()
batch_form = NewBatch()

最后,模板中表单的代码如下所示,我遍历一个列表(上面显示的“processesd_items_list”_其中列表中的每个元素都有一个附加的表单,在这种情况下可迭代的称为 items。第一种形式(UsedBatch)是:

<form method="POST">
    {{ items['used_form'].date.label }}{{ items['used_form'].date(class="uk-input") }}
    {{ items['used_form'].quantity.label }}{{ items['used_form'].quantity(class="uk-input") }}
    {{ items['used_form'].used_by.label }}{{ items['used_form'].used_by(class="uk-input") }}
    {{ items['used_form'].hidden_tag.label }}{{ items['used_form'].hidden_tag() }}
    {{ items['used_form'].submit() }}
</form>

第二种形式(NewBatch)是:

<form method="POST">
    {{ items['batch_form'].date.label }}{{ items['batch_form'].date(class="uk-input") }}
    {{ items['batch_form'].quantity.label }}{{ items['batch_form'].quantity(class="uk-input") }}
    {{ items['batch_form'].hidden_tag.label }}{{ items['batch_form'].hidden_tag() }}
    {{ items['batch_form'].submit() }}
</form>

谁能明白为什么它会提交 NewBatch 而不是 UsedBatch?当我只添加行时:

if batch_form.validate_on_submit():
    print('Batch submitted')
if used_form.validate_on_submit():
    print('Usage submitted')

在提交 UsedBatch 表单时,它返回“已提交的批量”而不是“提交的使用情况”。谁能帮忙指出原因?谢谢!

【问题讨论】:

    标签: flask flask-wtforms wtforms


    【解决方案1】:

    在您的 POST 路由上添加过滤器应该可以解决问题,请尝试以下操作:

    if batch_form.submit.data and batch_form.validate(): # notice the order 
        print('Batch submitted')
    if used_form.submit.data and used_form.validate(): # notice the order
        print('Usage submitted')
    

    当您调用 form.validate_on_submit() 时,无论单击哪个提交按钮,它都会检查表单是否通过 HTTP 方法提交。所以上面的小技巧只是添加一个过滤器(检查提交是否有数据,即batch_form.submit.data)。

    参考:Multiple forms in a single page using flask and WTForms

    【讨论】:

    • 这样做并更改提交按钮的名称(因此它们不都被命名为“提交”)解决了这个问题,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多