Denis
Denis

Reputation: 669

How to change values in Flask session dictionary using forms?

I'm writing shopping cart on Flask.

My cart based on session and forming dictionary like this:

[{'qty': 1, 'product_title': 'Post num six', 'product_id': 6}, 
{'qty': 1, 'product_title': 'Post five', 'product_id': 5}, 
{'qty': 1, 'product_title': 'Fouth post', 'product_id': 4}]

I need to change qty value in /cart route for every product in cart:

@app.route('/cart', methods=['GET', 'POST'])
def shopping_cart():
    page_header = "Cart"

    if request.method == 'POST' and 'update_cart' in request.form:                
        for cart_item in session["cart"]:
            cart_item["qty"] += 1 # this is wrong

            if cart_item["qty"] > 10:
                flash(u'Maximum amount (10) products in cart is reached', 'info')
                cart_item["qty"] = 10

        flash(u'update_cart', 'warning')

    return render_template('cart/cart.html', page_header=page_header)

Here is my cart.html template:

...
{% if session.cart %}

<form action="" method="post">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Name</th>
                    <th width="100">Qty</th>
                </tr>
            </thead>
            <tbody>
            {% for cart_item in session.cart %}
                <tr>
                    <td><a href="/post/{{ cart_item.product_id }}">{{ cart_item.product_title }}</a></td>

                    <td>
                        <div class="form-group">
                            <input class="form-control" type="number" name="change_qty" min="1" max="10" value="{{ cart_item.qty }}">
                        </div>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

    <div class="clearfix">
        <button type="submit" name="update_cart" class="btn btn-info pull-right">Update Cart</button>
    </div>
</form>

{% else %}
    <h2 style="color: red;">There is no cart session =(</h2>
{% endif %}

In cart.html covers all instances in cycle and adds change_qty input to change quantity of each product in cart.

The question is: how i can change quantity of each product in cart?

Upvotes: 0

Views: 2263

Answers (1)

Daniel W&#228;rn&#229;
Daniel W&#228;rn&#229;

Reputation: 788

The session object doesn't detect modifications to mutable structures automatically so you need to set session.modified = True yourself.

Upvotes: 3

Related Questions