15.1. Collecting POST data from cart

Next, we will retrieve the information received from the POST request.

We will modify the add_to_cart view function to accept all the request data in the form of a dictionary. Subsequently, we will extract the size and color ID data of the product from this dictionary.

views.py
def add_to_cart(request, product_id):
    if request.method == "POST" and product_id : #? if the user is sending a new product
        data = request.POST.dict() #? converts the request data to a dictionary
        size = data.get('size') #? used get instead of ['size] as it wont return a error
        color_id = data.get('color')
        print(size)
        if not size:
            return redirect('store')
        return redirect('cart')
    else :
        return redirect('store') #? redirect the user to the store if he didn't choose a product

Following that, in the view_product function, we will update the variable selected_color_name to selected_color, allowing us to reference the entire color object, facilitating the gathering of its ID from the form section of the view_product.html.

views.py
selected_color = None
    product = Product.objects.get(id=product_id) #? id parameter is created automatically by django
    item_stock = ItemStock.objects.filter(product = product, quantity__gt = 0) #? gets the product that has more than 0 quantity (queryset lookup)
    if len(item_stock) > 0 : 
        has_stock = True #? necessary in order to do a if on the html. if the product is out of stock, will show "Out of Stock"
        colors = {item.color for item in item_stock} #? gets the colors of all products, uses sets '{}' to avoid duplicate colors
        if id_color :
            selected_color = Color.objects.get(id = id_color) #? gets the color object from the Color class
            item_stock = ItemStock.objects.filter(product = product, quantity__gt = 0, color__id = id_color) #? gets the color id  attribute from the Color class (that is automatically created)
            sizes = {item.size for item in item_stock} #? gets the sizes of all products
    context = {'product': product, "has_stock" : has_stock, "colors" : colors, "sizes" : sizes, "selected_color" : selected_color}

Additionally, we will update the names within the view_product.html file accordingly.

view_product.html
{% if selected_color %}

Color: {{ selected_color.name }}

{% endif %}

Before the submit button line in the form section, we will append the color data to the POST request by incorporating a input tag of type hidden (as it will have already been selected by the user):

view_product.html
<input type="hidden" name="color" value="{{ selected_color.id }}">

Last updated