19. Cart update for anonymous users
Adding products
import uuiddef 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')
if not size: #? only check the size as it only appears after selecting the color
return redirect('store')
#!getting the client
answer = redirect('cart') #? to implement cookies we need to edit the redirect response
if request.user.is_authenticated:
client = request.user.client
else :
if request.COOKIES.get("id_session") : #? checks if there is already a registred anonymous session
id_session = request.COOKIES.get("id_session")
else :
id_session = str(uuid.uuid4()) #? uuid4 guarantees uniqueness and safety
answer.set_cookie(key="id_session", value=id_session)
client, created = Client.objects.get_or_create(id_session=id_session)
order, created = Order.objects.get_or_create(client=client, finished=False)
item_stock = ItemStock.objects.get(product__id=product_id, size=size, color=color_id) #? In the forms we enter the color, id, and the size
item_ordered, created = OrderedItem.objects.get_or_create(order=order, itemstock=item_stock) #? adding the product to the cart
item_ordered.quantity += 1
item_ordered.save() #? Must save changes made directly to a element
return answer
else :
return redirect('store') #? redirect the user to the store if he didn't choose a product



Removing products
Last updated