【问题标题】:How to display that the shopping cart is empty - Flask如何显示购物车为空 - Flask
【发布时间】: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'”

标签: python flask cart webshop


【解决方案1】:

如果您也将 product_id 作为变量传递会怎样。

试试这个:

return render_template('cart.html', product=product, product_id=product_id ,totalprice=totalprice)

并修改这一行:

{% if session['amount'] == '0' or {{product_id}} == None %}

【讨论】:

  • 感谢您的建议!不幸的是,我仍然遇到同样的错误:/
  • 不应该是 str ('None') 吗?