gpt4 book ai didi

python - Flask 应用程序中的数据未提交到数据库

转载 作者:行者123 更新时间:2023-11-30 21:27:30 25 4
gpt4 key购买 nike

我正在做一个 Flask 应用程序。那里一切正常,但是当表单试图在数据库中插入值时出现问题。我调试了代码,发现 add_warehouse() 中的 request.method == 'POST' 没有被触发。

aap.py

# Show Warehouse stocks
@app.route('/dashboard/warehouse', methods=['POST','GET'])
@is_logged_in
def warehouse():
form = Add_Warehouse(request.form)
cur = mysql.connection.cursor()
result = cur.execute('SELECT * from company_warehouse')
data = cur.fetchall()
if result>0:
return render_template('warehouse.html', stocks=data, form=form)
else:
return render_template('warehouse.html',msg='Stock Empty', form=form)
cur.close()

# Add Warehouse Stocks
class Add_Warehouse(Form):
product_name = StringField('Name',[validators.Length(min=5,max=20), validators.DataRequired()])
product_qty = IntegerField('Quantity',[validators.DataRequired()])
product_price = DecimalField('Price',[validators.DataRequired()])

@app.route('/add_warehouse',methods=['POST','GET'])
@is_logged_in
def add_warehouse():
form = Add_Warehouse(request.form)
if request.method == 'POST' and form.validate():
product_name = form.product_name.data
product_qty = form.product_qty.data
product_price = form.product_price.data
app.logger.info(product_name,product_qty,product_price)
cur = mysql.connection.cursor()
cur.execute('INSERT INTO company_warehouse(PRODUCT_NAME,QTY,PRICE_PER_UNIT) VALUES(%s,%s,%s)',(product_name,product_qty,product_price))
mysql.connection.commit()
flash('Product Added !!','success')
return redirect(url_for('warehouse'))
cur.close()

warehouse.html

{% from 'includes/_formhelpers.html' import render_field %}
{% include 'includes/_messages.html' %}
<form method="POST" action="">
<div class="modal-body">
<div class="form-group">{{render_field(form.product_name, class_="form-control")}}</div>
<div class="form-group">{{render_field(form.product_qty, class_="form-control")}}</div>
<div class="form-group">{{render_field(form.product_price, class_="form-control")}}</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add Product</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
</form>

这是上述代码的模板。我之前曾尝试过写作,因为我认为这会造成问题 action = "{{url_for('add_warehouse')}}" 但没有任何改变。

最佳答案

我认为这是因为您缺少 action form 中的属性.

试试这个 <form method="POST" action="/add_warehouse">

关于python - Flask 应用程序中的数据未提交到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com