15. POST method on cart

Now we will focus on enhancing the cart section of our website. It is important to ensure that the cart functionality accommodates both logged-in and non-logged-in users, enabling them to create and manage orders seamlessly.

Until now, we have primarily utilized GET methods to retrieve information from the website, such as displaying specific pages. For the cart functionality, we will use the POST method, as it allows us to send data to the website or database. This method will be used to add the product that the user wishes to purchase to the cart.

To start, we will modify the if sizes section of our view_product.html file to include a form that allows data to be send to the website via the Add to cart button. This will enable users to add products to their cart. Below is the revised code:

view_product.html
{% if sizes %}
<form method = "POST" action = "{% url 'add_to_cart' product.id %}"> <!--Forms in django need to specify its method, action (where it will be sent)-->
    {% csrf_token %} <!--Protects (by generating a unique token) the forms from hackers trying to replicate it-->
    <p>Select the size:</p>
    {% for size in sizes %}
    <input type="radio" name="size" value="{{ size }}"> <!--Radio button -> choose one option, all connected to the same name. Value is what is sent to the website-->
    <label for= "{{ size }}">{{ size }}</label> <!--Button text, for tag vinculates each button the the size-->
    {% endfor %}

    <button type = "submit">Add to Cart</button> <!--Button type submit is used to send the form its in-->
</form>
{% endif %}
  • The initial form tag includes a 'method' attribute, set to POST, indicating that the form data will be transmitted to the server. Additionally, the 'action' attribute specifies the target URL where the form data will be processed.

  • The {% csrf_token %} line safeguards forms from cross-site request forgery (CSRF) attacks by generating a unique token for each form submission. This token ensures that the request originates from the legitimate user and not from a malicious source.

  • Subsequently, the sizes were converted into radio buttons, each assigned specific values and labels corresponding to their respective options.

  • Finally, the "Add to Cart" button was implemented with the attribute type="submit", enabling it to transmit the collected data from the whole form section to the website upon submission.

Sizes became radio buttons with labels

Within the views.py file, we will define a new view function named add_to_cart. This function will handle the URL information and process the request when a user adds a product to the cart.

For now, if the user successfully adds a new product, the function will print a message stating "form sent" along with the product_id, and then redirect the user to the cart URL. Otherwise, it will redirect the user to the store URL.

views.py
def add_to_cart(request, product_id):
    if request.method == "POST" and product_id : #? if the user is sending a new product
        print("Form sent!", product_id)
        return redirect('cart')
    else :
        return redirect('store') #? redirect the user to the store if he didn't choose a product
    path('addtocart/<int:product_id>/', add_to_cart, name="add_to_cart"), 

The difference between redirect() and render() is that we chose to use redirect() instead of render() because the add_to_cart function is designed to perform a backend action without generating a specific HTML response. Instead, it redirects the user to another view or URL, such as the cart or store views, which already have their own dedicated HTML templates.

Remember to include the path of the new URL in the urls.py file. As each URL will vary according to the product ID, we will incorporate it into the URL pattern.

Important note: End ALL your urls inside the path function with a '/'.

store/urls.py
path('addtocart/<int:product_id>/', add_to_cart, name="add_to_cart"), 

Finally, we will remove the item_stock element from the context dictionary within the view_product function, as it will not be referenced in our HTML file.

views.py
context = {'product': product, "has_stock" : has_stock, "colors" : colors, "sizes" : sizes, "selected_color_name" : selected_color_name}
Pressing "Add to Cart" redirects the user to the cart URL, and the message containing product_id is printed on the console.

Last updated