20. Cart visualization for anonymous users.

Now, we will modify our cart function to enable access for anonymous users.

views.py
def cart(request):
    #! getting the client
    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
            context = {"existing_client": False, "order" : None, "items_ordered" : None}
            return render(request, 'cart.html', context)

    order, created = Order.objects.get_or_create(client=client, finished=False) 
    items_ordered = OrderedItem.objects.filter(order = order)
    context = {"order" : order, "items_ordered" : items_ordered, "existing_client": True}
    return render(request, 'cart.html', context) 

The modifications implemented in the updated code are detailed below:

  • 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:

    • else:

      • Handles the scenario for non-authenticated (anonymous) users.

    • 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.

      • client, created = Client.objects.get_or_create(id_session=id_session)

        • Retrieves or creates a Client object associated with the id_session. If the Client object does not exist, it will be created.

    • Handle Direct Access to Cart Without Cookies:

      • else:

        • Executes if no id_session cookie is found, meaning the user has entered directly into the cart without generating cookies.

      • context = {"existing_client": False, "order": None, "items_ordered": None}

        • Prepares a context dictionary indicating there is no existing client, no order, and no items ordered.

      • return render(request, 'cart.html', context)

        • Renders the cart.html template with the prepared context data, displaying an empty cart to the user.

Finally, we will modify the cart.html file by enclosing the entire body block within a conditional statement that checks for the existence of a client. If the client does not exist, indicating an empty cart, an appropriate message will be displayed:

We can now access the cart content as an anonymous user:

Note that the cart quantity count remains at 0. This is due to the need to modify the new_context.py code to accommodate anonymous users.

Last updated