21. Display product quantity for anonymous user
Next, we will implement functionality to display the product quantity within the cart for anonymous users. The process will be analogous to the previous implementation, which allowed the cart to be viewed and updated by anonymous users.
We will integrate the same code from the previous section into the cart
function of the new_context.py
file. This file is responsible for displaying the product quantity across all HTML templates.
def cart(request) :
product_amount_cart = 0
if request.user.is_authenticated:
client = request.user.client #? one to one relationship
else :
if request.COOKIES.get('id_session') :
id_session = request.COOKIES.get("id_session")
client, created = Client.objects.get_or_create(id_session=id_session)
else : #? if the client enters directly on the cart, whithout generating cookies
return {"product_amount_cart" : product_amount_cart} #? return initial quantity, which is 0
In the code above, we implemented a check to verify if the user has an id_session
generated by cookies. If the id_session
does not exist, indicating the user accessed the cart directly without adding a product, the function returns the initial product quantity of 0.

Last updated