I'm trying to get multiple items to display in my Flask shopping cart. I want to append the list of product dictionaries in cart_list to a new list of all cart dictionaries in append_list, and display the append_list values in my Flask template in cart.html.
- How do I parse the values from the new "appended" dictionaries list in
append_list? Would appreciate any help (please)!! (Stripped out my variables (below) with static values for testing purposes.)
Flask code
@app.route('/<int:id>/cart', methods=['GET', 'POST'])
def add_to_cart(id):
tag = get_tag(id)
try:
product_quantity = 300
user_quantity = 10
if user_quantity > product_quantity:
flash("Please enter a lower quantity.")
return render_template('tag.html', tag=tag)
else:
tag_id = 12
product = "Title"
price = 300
sub_total = "{:.2f}".format( user_quantity * price )
price = "{:.2f}".format(price)
json = {
"id": tag_id,
"product": product,
"price": price,
"user-quantity": user_quantity,
"product-quantity": product_quantity,
"subtotal": sub_total
}
cart_list = []
cart_list.append(json)
append_list = []
for item in cart_list:
ele = item
append_list.append(ele)
print(append_list)
flash("Added to cart.")
except Exception as e:
print(e.args)
return render_template('cart.html', tag=tag, sub_total=sub_total, cart_list=cart_list, append_list=append_list)
Json I need
User adds item to cart, add to append_list.
append_list = [
{
"id": tag_id,
"product": product,
"price": price,
"user-quantity": user_quantity,
"product-quantity": product_quantity,
"subtotal": sub_total
},
{
"id": tag_id,
"product": product,
"price": price,
"user-quantity": user_quantity,
"product-quantity": product_quantity,
"subtotal": sub_total
}
]
etc.
cart.html
Currently my code in cart.html is successfully parsing only one product dictionary (cart_list.append(json)). I keep erroring out when parsing dictionary values from append_list.
{% for item in cart_list %}
<tr>
<td>{{ cart_list[0]['product'] }}</td>
<td>{{ cart_list[0]['price'] }}</td>
<td>{{ cart_list[0]['user-quantity'] }}</td>
<td>{{ cart_list[0]['subtotal'] }}</td>
</tr>
{% endfor %}