Adding products to the cart

Now, we need to add an Add to cart button to the product detail page. Edit the views.py file of the shop application, and add CartAddProductForm to the product_detail view as follows:

from cart.forms import CartAddProductForm

def product_detail(request, id, slug):
product = get_object_or_404(Product, id=id,
slug=slug,
available=True)
cart_product_form = CartAddProductForm()
return render(request,
'shop/product/detail.html',
{'product': product,
'cart_product_form': cart_product_form})

Edit the shop/product/detail.html template of the shop application, and add the following form to the product's price as follows:

<p class="price">${{ product.price }}</p>
<form action="{% url "cart:cart_add" product.id %}" method="post">
{{ cart_product_form }}
{% csrf_token %}
<input type="submit" value="Add to cart">
</form>
{{ product.description|linebreaks }}

Make sure the development server is running with the command python manage.py runserver. Now, open http://127.0.0.1:8000/ in your browser and navigate to a product's detail page. It now contains a form to choose a quantity before adding the product to the cart. The page will look like this:

Choose a quantity and click on the Add to cart button. The form is submitted to the cart_add view via POST. The view adds the product to the cart in the session, including its current price and the selected quantity. Then, it redirects the user to the cart detail page, which will look like the following screenshot:

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

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