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:

cart.html
{% block body %}

{% if existing_client %}

    <h3>Cart</h3>

    <h4>Order ID: {{ order.id }}</h4>
    <p>Total Price: R$ {{ order.total_cost }}</p>
    <p>Total Quantity: {{ order.total_quantity }}</p>
    {% for item in items_ordered %}
    <p>
        <img src="{{ item.itemstock.product.image.url }}" width = "60" height = "80">
        Product: {{ item.itemstock.product.name }}; 
        Color: {{ item.itemstock.color.name }}; 
        Size: {{ item.itemstock.size }}; 
        
        <div style="display:flex;"> <!--Makes eveyrything in the same line-->
            Quantity: 
            <!--! REMOVE BUTTON -->
            <form method = "POST" action = "{% url 'remove_from_cart' item.itemstock.product.id %}"> <!--? Changed the product reference to the one being used in the code above-->
                {% csrf_token %} <!--Protects (by generating a unique token) the forms from hackers trying to replicate it-->
                <input type="hidden" name="size" value="{{ item.itemstock.size }}">
            <input type="hidden" name="color" value="{{ item.itemstock.color.id }}">
            <button type="submit">-</button> 
            </form>

            {{ item.quantity}}
            <!--! ADD BUTTON -->
            <form method = "POST" action = "{% url 'add_to_cart' item.itemstock.product.id %}"> <!--? Changed the product reference to the one being used in the code above-->
                {% csrf_token %} <!--Protects (by generating a unique token) the forms from hackers trying to replicate it-->
            <input type="hidden" name="size" value="{{ item.itemstock.size }}">
            <input type="hidden" name="color" value="{{ item.itemstock.color.id }}">
            <button type="submit">+</button> 
            </form>;
        </div>
        Unit Price: {{ item.itemstock.product.price }}; 
        Total Price: R${{ item.total_price }}
    </p>
    <hr> <!--Horizonal row-->
    {% endfor %}
    <a href = "{% url 'checkout' %}">Checkout</a>

{% else %}

    <h3>Your cart is empty</h3>
    <a href = "{% url 'store' %}">Visit our store</a>

{% endif %}

{% endblock %}

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