如何使用表单改变Flask会话字典中的值



我在Flask上写购物车。

我的购物车基于会话和形成字典,像这样:

[{'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}]

我需要更改/cart路由中每个产品的qty值:

@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)

这是我的cart.html模板:

...
{% 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涵盖循环中的所有实例,并添加change_qty输入来更改购物车中每个产品的数量。

问题是:我如何改变每个产品在购物车中的数量?

会话对象不会自动检测对可变结构的修改,所以您需要设置session.modified = True自己。

最新更新