19. Cart update for anonymous users
Adding products
Our website will support purchases by anonymous customers who do not have an account throught the use of cookies (that generate and store unique ids for each user that enters). To facilitate this, first we will implement a system that automatically generates a customer ID upon adding a item to the cart.
Important Note: At present, the shopping cart functionality is restricted to authenticated users (specifically the admin user). Ensure you are logged into your admin account, as the cart will not function without authentication.
We will begin by importing the uuid
(Universal Unique Identifier) library into the views.py
file. This library will be responsible for generating unique identifiers.
import uuid
Next, we will modify the is_authenticated
condition check within our add_to_cart
function to generate a unique customer ID if the user does not have an existing account.
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')
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
The modifications implemented in the updated code are detailed below:
Redirect Initialization:
answer = redirect('cart')
Initializes a redirect response to the 'cart' view.
Authenticated User Check:
if request.user.is_authenticated:
Checks if the user is authenticated.
client = request.user.client
Retrieves the authenticated user's client object.
Anonymous User Handling:
Check for Existing Anonymous Session:
if request.COOKIES.get("id_session"):
Checks if an
id_session
cookie already exists in the user's cookies.
id_session = request.COOKIES.get("id_session")
Retrieves the existing
id_session
value.
Generate New Anonymous Session ID:
else:
Executes if no
id_session
cookie is found.
id_session = str(uuid.uuid4())
Generates a new unique identifier using
uuid4
, ensuring a unique ID independent of the user's device.
answer.set_cookie(key="id_session", value=id_session)
Sets a new cookie with the key
id_session
and the generated unique ID.
Client Object Retrieval/Creation:
client, created = Client.objects.get_or_create(id_session=id_session)
Retrieves or creates a
Client
object associated with theid_session
. If theClient
object does not exist, it will be created.
Upon logging out of the admin account and attempting to add an item to the cart, the following error message will be encountered:

Upon logging back into the admin account, it will be observed that a new client and order have been created, with the client name displayed as None.


Removing products
The process for enabling product removal is akin to the recent implementation. We will proceed to modify the remove_from_cart
function accordingly.
if request.user.is_authenticated:
client = request.user.client
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 redirect('store') #? return directly to the store as the cart should be empty
In the updated remove_from_cart
function, we have incorporated similar logic to handle anonymous clients. If no id
is found (indicating the client accessed the cart directly without adding a product), a redirect to the store is implemented, ensuring an empty cart state.
Last updated