Flask update product quantity in Session


I’m trying to create a small ecommerce shop using Flask. Everything is going very well except for the cart phase. I want the app to increase the quantity of the product in the cart instead of adding the same product twice.

For example, when I click "Add to cart" twice, the data saved in the session is this:

[{'product': '5', 'quantity': 1}]
[{'product': '5', 'quantity': 1}]

I want it to be saved as this:

[{'product': '5', 'quantity': 2}]

Here is my current code:

@app.route('/item/<id>', methods=['POST', 'GET'])
def item_page(id):
    form = add_to_cart()
    if form.validate_on_submit():
        if 'cart' in session:
            session['cart'].append({'id' : form.id.data, 'quantity' : form.quantity.data})
            session.modified = True
    return render_template('product.html', form=form)

I found a similar question answered here but the solution didn’t work for me:
Flask python where should I put goods that go to cart in online shop?


You are appending to a list so you are always creating a new row.

You need to check if the product already exists in the list of items in the cart and if so, you increment the quantity. Something like (this is very rough code)

    # Get a temporary reference to the session cart, just to reduce the name of the variable we will use subsequently
    cart = session["cart"]

    # This flag will be used to track if the item exists or not
    itemExists = False

    # Iterate over the cart contents and check if the id already exists
    for index, value in enumerate(cart):
        if value["id"] == form.id.data:
            cart[index]["quantity"] = cart[index]["quantity"] + form.quantity.data
            itemExists = True
            break # exit the for loop 

    # if the item does not exist, then you create a new row
    if not itemExists:
        cart.append({'id' : form.id.data, 'quantity' : form.quantity.data})
    # Save the temp cart back into session
    session["cart"] = cart

Answered By – NoCommandLine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published