I am creating a e-commerce website with Django and I stumbled onto a problem I cannot solve.
If i click on add to cart button, the added product shows up in the shopping cart. However, if i navigate to lets say home page ( or any other page ) the newly added product is not displayed no more in the shopping cart.

In JS file I have added some code for debugging.
In views I have done the same, although with the current code I have parsed in here, most of the logging is already removed.

Any suggestions how I can solve this?

I have added logging to server side to debug. I have solved quite a bit there already.

On the client side ( atleast, thats what i suspect where the rootcause may lie), the logging is still there.

views:

def add_to_cart(request):
    try:
        cart_product = {
            "product_name": request.GET["product_name"],
            "product_price": request.GET["product_price"],
            "product_quantity": int(request.GET["product_quantity"]),
        }
        
        product_id = str(request.GET["product_id"])

        if "cart_data_obj" in request.session:
            cart_data = request.session["cart_data_obj"]
            
            if product_id in cart_data:
                # Product already exists in the cart, update the quantity
                cart_data[product_id]['product_quantity'] += int(cart_product['product_quantity'])
            else:
                # Product doesn't exist, add it to the cart
                cart_data[product_id] = cart_product
            
            request.session["cart_data_obj"] = cart_data
        else:
            # Cart is empty, initialize it with the current product
            cart_data = {product_id: cart_product}
            request.session["cart_data_obj"] = cart_data

        # Calculate total quantity for all products in the shopping cart
        total_quantity_cart = sum(product_data['product_quantity'] for product_data in cart_data.values())
        request.session["total_quantity_cart"] = total_quantity_cart

        return JsonResponse({
            "data": request.session["cart_data_obj"],
            "totalcartitems": len(request.session["cart_data_obj"]),
            "total_quantity_cart": request.session["total_quantity_cart"]
        })

    except Exception as e:
        print(e)
        return HttpResponse(status=500)

JS :

$(document).ready(function () {
    // Bind the cartUpdated event listener once when the document is ready
    $(document).on('cartUpdated', function () {
        // Add code here to update other elements on the page
        console.log('Cart Updated. Update other UI elements if needed.');
    });

    $("#add_to_cart_btn").on("click", function () {
        let product_quantity = 1;
        let product_id = $(this).closest('.col-12').find('.product_name').attr('id').split('_')[1];
        let product_name = $(".product_name").text();
        let product_price = $(".product_price").text();
        let this_val = $(this);

        console.log("Product ID : ", product_id);
        console.log("Product Name : ", product_name);
        console.log("Product Price : ", product_price);
        console.log("Product Quantity", product_quantity);
        console.log("Current Element : ", this_val);

        // preparing data from client side to get called in server side
        $.ajax({
            url: "/cart/",
            data: {
                "product_id": product_id,
                "product_name": product_name,
                "product_price": product_price,
                "product_quantity": product_quantity,
            },
            dataType: "json",
            beforeSend: function () {
                console.log("Adding products to cart...");
            },
            success: function (response) {
                console.log("Success Response:", response);

                if (response.total_quantity_cart !== undefined) {
                    $(".cart_items_count").text(response.total_quantity_cart);
                    console.log("Total Quantity Updated:", response.total_quantity_cart);
                } else {
                    console.log("Error: 'total_quantity_cart' not found in response.");
                }

                this_val.html("Item Added To Cart!");
                // Trigger the cartUpdated event
                $(document).trigger('cartUpdated');
            },
            error: function (xhr, status, error) {
                console.log("Error:", error);
            },
            complete: function () {
                console.log("Request complete");
            }
        });
    });
});

html element:

<a class="nav-link active" aria-current="page" href="#">Shopping Cart<span class="badge rounded-pill cart_items_count">{{ total_quantity_cart }}</span></a>

New contributor

Cryptias is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.