How to display that the shopping cart is empty - Flask

414 Views Asked by At

I am creating a webshop using Flask. For the moment, I am trying to display a message when the shopping cart is empty. I have already managed to display the message when the amount of 0 of a product is added to the cart, using an if-test. But I fail to display a message when no amount of the product is added to the cart (the bold piece of code (between *) is where the error message appears)).

This is my route function in 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)

This is my html-file of the cart (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 %}

Thank you in advance!

1

There are 1 best solutions below

2
Marya On

What if you pass the product_id as a variable as well.

try this :

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

and modify this line:

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