wtforms提交错误的表单

问题描述 投票:0回答:1

我正在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'_,其中列表中的每个元素都有一个附加的表单,在这种情况下,可迭代的称为item。第一种形式(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>

谁能看到为什么它要通过UsedBatch提交NewBatch?当我只添加行时:

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

在提交UsedBatch表单时,它返回“批处理已提交”而不是“用法已提交”。谁能帮忙指出原因?谢谢!

flask flask-wtforms wtforms
1个回答
0
投票

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

if batch_form.submit.data and batch_form.validate(): # notice the order 
....
if used_form.submit.data and used_form.validate(): # notice the order
....

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

© www.soinside.com 2019 - 2024. All rights reserved.