I'm working on an online shop, and I'm having a problem in the cart,
here's a screen shot (
http://pasteboard.co/Vwnv2T0.png).
I'd like the form for each item (product) to show it's current quantity (that's already been added to the cart)
as an initial value as most ecommerce sites do.
I've tried iterating through the items in the cart (in views.show_cart) then adding the form,
however the form for all items in the cart shows the exact same value (of the last item).
In other words, there's 2 items in the cart, one has a quantity of 7 and the other a quantity of 3,
but both forms show the quantity as 3.
I can't figure out how to correct this, although I'm sure it's a simple fix.
Thanks in advance for the help, and I hope this question is formatted correctly?
Here's the code on github if it helps. . .
https://github.com/chriskavanagh/ecommerce/tree/master/src# form
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class ProductAddToCartForm(forms.Form):
quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int)
update = forms.BooleanField(required=False,initial=False,widget=forms.HiddenInput(attrs={'class': 'form-control'}))
# views (cart_id.views.show_cart)
def show_cart(request):
cart_id = _cart_id(request)
cart_items = CartItem.objects.filter(cart_id=cart_id)
for item in cart_items:
q = item.quantity
print q #shows correct value (quantity) of each item in cart
add_product_form = ProductAddToCartForm(initial={'quantity': q})
context = {'cart_items': cart_items, 'add_product_form': add_product_form}
return render(request, 'cart_id/cart.html', context)
# template (cart.html)
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %}Shopping Cart{% endblock %}
{% block content %} {% endblock %}
{% block extra_content %}
<div class="container">
<div class="col-md-12">
<h2>Cart</h2>
<caption><b>Your Shopping Cart:</b> {{ cart_items_count }} Items In Your Cart.</caption>
<hr>
{% for item in cart_items %}
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="{{ item.product.get_absolute_url }}">{{ item.product }}</a></td>
<td>${{ item.product.price }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.total }}</td>
<td>
<div class="form-group">
<form action="{% url 'cart:add' item.product.slug %}" method="POST">
{% csrf_token %}
<div class="col-xs-3">
{{ add_product_form.quantity }}
</div>
{{ add_product_form.update }}
<input class='btn btn-success btn-sm' type='submit' value='Update'/>
</form>
</div>
</td>
</tr>
</tbody>
</table>
{% empty %}
<h3>You Have Nothing In Your Cart.</h3>
{% endfor %}
</div>
</div>
{% endblock %}