我正在使用 Django 创建一个电子商务网站,我偶然发现了一个无法解决的问题。 如果我单击“添加到购物车”按钮,添加的产品将显示在购物车中。但是,如果我导航到主页(或任何其他页面),新添加的产品将不再显示在购物车中。
在JS文件中我添加了一些用于调试的代码。 在视图中我也做了同样的事情,尽管使用我在这里解析的当前代码,大部分日志记录已经被删除。
有什么建议我可以解决这个问题吗?
我已将日志记录添加到服务器端以进行调试。我已经解决了很多问题。
在客户端(至少,这就是我怀疑根本原因所在),日志记录仍然存在。
浏览次数:
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 元素:
<a class="nav-link active" aria-current="page" href="#">Shopping Cart<span class="badge rounded-pill cart_items_count">{{ total_quantity_cart }}</span></a>
目前您的 {{total_quantity_cart }} 仅在 ajax success 函数中设置并写入页面。如果您希望它在加载页面时显示会话对象中的金额,您可以使用
{{ request.session.total_quantity_cart }}
在您的模板中。