【发布时间】:2024-04-24 22:00:01
【问题描述】:
我正在使用 Flask 创建一个网上商店。目前,我正在尝试在购物车为空时显示一条消息。当产品的数量为 0 被添加到购物车时,我已经使用 if-test 设法显示消息。但是,当没有将任何数量的产品添加到购物车时,我无法显示消息(粗体代码(在 * 之间)是错误消息出现的位置)。
这是我在 Python 中的路由函数:
@app.route('/cart', methods=['GET', 'POST'])
def cart():
product_id = session['product_id']
product = my_products[product_id]
totalprice = int(session['amount']) * product['price']
return render_template('cart.html', product=product, totalprice=totalprice)
这是我的购物车 html 文件 (cart.html):
{% if session['amount'] == '0' or **product_id == None** %}
<p>You have no products in your cart.</p>
<div id="place_order">
<button id='btnalert' disabled>place order</button>
</div>
{% else %}
<p>You have in your cart:</p>
<p>Product: {{product['name']}}</p>
<p>Price: {{product['price']}}</p>
<p>Amount: {{session['amount']}}</p>
<p id="totalprice">TOTAL PRICE: {{totalprice}}</p>
<div id="place_order">
<button id='btnalert'>place order</button>
<script>
btnAlert = document.querySelector('#btnalert')
function showAlert() {
alert('Sorry, this shop is out of business!')
}
btnAlert.addEventListener("click", showAlert)
</script>
</div>
{% endif %}
提前谢谢你!
【问题讨论】:
-
你能分享一下错误信息的内容吗?
-
它只是给出一个 500 内部服务器错误,说“服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。”当我查看终端时,它显示“KeyError:'product_id'”