Updating product quantities in the cart

When users see the cart, they might want to change product quantities before placing an order. We are going to allow users to change quantities from the cart detail page.

Edit the views.py file of the cart application and change the cart_detail view to this:

def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(
initial={'quantity': item['quantity'],
'update': True})
return render(request, 'cart/detail.html', {'cart': cart})

We create an instance of CartAddProductForm for each item in the cart to allow changing product quantities. We initialize the form with the current item quantity and set the update field to True so that when we submit the form to the cart_add view, the current quantity is replaced with the new one.

Now, edit the cart/detail.html template of the cart application and find the following line:

<td>{{ item.quantity }}</td>

Replace the previous line with the following code:

<td>
<form action="{% url "cart:cart_add" product.id %}" method="post">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Update">
{% csrf_token %}
</form>
</td>

Open http://127.0.0.1:8000/cart/ in your browser. You will see a form to edit the quantity for each cart item, shown as follows:

Change the quantity of an item and click on the Update button to test the new functionality. You can also remove an item from the cart by clicking the Remove link.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset