【发布时间】:2020-08-04 15:50:27
【问题描述】:
我之前发布了这个问题,但后来它被链接到一个类似的问题,该问题没有提供所需的解决方案,然后被关闭以供回答。
所以我创建了一个 Flask 应用程序来跟踪产品从一个位置到另一个位置的移动,同时我通过 Flask 应用程序进行移动表单没有得到验证我尝试将 {{ form.hidden_tag() }} 和 {{ form.csrf_token }} 添加到 html 文件接受用户的输入。
如果我在命令行上从终端运行此应用程序,表单将被验证并添加到数据库中,但如果我运行烧瓶应用程序并在浏览器中提交表单,则不会。
这是我的代码
class MovementForm(FlaskForm):
to_location = SelectField('To Location', coerce=int)
from_location = SelectField('From Location', coerce=int)
product = SelectField('Product')
quantity = IntegerField('Quantity')
add_movement = SubmitField('Add Movement')
@app.route('/movements',methods=["GET","POST"])
def add_movements():
form = MovementForm()
form.to_location.choices = [(location.id, location.location_name) for location in Location.query.all()]
form.from_location.choices = [(location.id, location.location_name) for location in Location.query.all()]
form.product.choices = [(product.id, product.product_name) for product in Product.query.all()]
form.from_location.choices.insert(0, (0, 'None'))
if form.validate_on_submit():
new_movement = Movement(to_location_id=form.to_location.data, from_location_id=form.from_location.data, product_id=form.product.data, quantity=form.quantity.data)
db.session.add(new_movement)
db.session.commit()
flash('Product has been moved!', 'success')
return redirect(url_for('add_movements'))
return render_template('add_movements.html', form=form)
这是我的 html 文件
<form action="/movements" method="post">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
<div class="row">
<div class="form-group col">
{{ form.from_location.label(class="form-control-label") }}
{{ form.from_location(class="form-control form-control-lg") }}
</div>
<div class="form-group col">
{{ form.to_location.label(class="form-control-label") }}
{{ form.to_location(class="form-control form-control-lg") }}
</div>
</div>
<div class="row">
<div class="form-group col">
{{ form.product.label(class="form-control-label") }}
{{ form.product(class="form-control form-control-lg") }}
</div>
<div class="form-group col">
{{ form.quantity.label(class="form-control-label") }}
{{ form.quantity(class="form-control form-control-lg") }}
</div>
</div>
<div class="form-group">
{{ form.add_movement(class="btn btn-outline-info") }}
</div>
</form>
这里有什么问题?
【问题讨论】:
-
我认为问题在于表单返回 false 因此在 `if form.validate_on_submit():` 之后的所有内容都不会运行,因为返回 False
标签: python flask flask-wtforms