I'm trying to make simple cart system to the online shop using Python and framework - Flask. I'm getting data from form in products.html then writing it into the session. I have a problem with getting this data and returning it to the cart.html - I'm get just clear page instead of names of the products i added to the cart.
products.html
{% for el in products %}
<p>Name {{ el.product_name }}</p>
<p>Description {{ el.product_description }}</p>
<p>Image </p> <img width="200" height="200" src="data:;base64,{{ el.product_img }}">
<p>Cost: {{ el.product_cost }} тенге.</p>
<form method="post" action="/cart">
<input type="hidden" name="cart_prod_name" value="{{ el.product_name }}">
<input type="submit" value="Add to cart">
</form>
{% endfor %}
Python function cart()
:
@app.route('/cart', methods=['POST', 'GET'])
def cart():
if 'cart' not in session:
session['cart'] = []
if request.method == 'POST':
cart_prod_name = request.form['cart_prod_name']
session['cart'] += cart_prod_name
return redirect('/cart')
if request.method == 'GET':
cart_products = session['cart']
return render_template('cart.html', cart_products=cart_products)
cart.html:
{% for cart_product in cart_products %}
<p>{{ cart_product.order_prod_name }}</p>
{% endfor %}
From flask.session
docs:
Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself.
your carts holder object is a mutable structure == list so you have to set after changes
session.modified = True
I sloved that problem. Exactly I needed to iterate cart_product
in cart_roducts
and output cart_product
and don't call it to output order_prod_name
.
Fixed cart.html
:
{% for cart_product in cart_products %}
<p>{{ cart_product }}</p>
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.