Django Cart View: Total Amount Showing 0
I’m encountering an issue with my Django cart view where the total cart amount is showing as 0. Below are the relevant parts of my code and the logs.
JavaScript (AJAX):
$(document).ready(function() {
$("#add-to-cart-btn").on("click", function(){
let quantity = $("#product-quantity").val();
let product_title = $(".product-title").val();
let product_id = $(".product-id").val();
let product_price = $("#current-product-price").text();
let product_image = $(".product-image").val();
let product_pid = $(".product-pid").val();
let this_val = $(this);
// Log the values
console.log("Quantity:", quantity);
console.log("Id:", product_id);
console.log("PId:", product_pid);
console.log("Image:", product_image);
console.log("Title:", product_title);
console.log("Price:", product_price);
console.log("Current Element:", this_val);
// Check if product price is valid
if (!product_price || isNaN(parseFloat(product_price))) {
console.error("Product price is invalid: " + product_price);
return;
}
$.ajax({
url: '/add-to-cart',
data: {
'id': product_id,
'pid': product_pid,
'image': product_image,
'qty': quantity,
'title': product_title,
'price': product_price
},
dataType: 'json',
beforeSend: function(){
console.log("Adding products to cart");
},
success: function(res){
this_val.html("Go to Cart");
console.log("Added products to cart");
$(".cart-items-count").text(res.totalcartitems);
$(".total").text(res.cart_total_ammount);
}
});
});
});
Django View:
from decimal import Decimal, InvalidOperation
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Coupon
def cart_view(request):
cart_total_amount = 0
coupon_discount_decimal = Decimal(0)
coupon_code = ""
coupon_discount_percentage = 0
if 'cart_data_obj' in request.session:
print("Cart Data:", request.session['cart_data_obj']) # Log cart data
for p_id, item in request.session['cart_data_obj'].items():
try:
item_price = float(item['price'])
except (ValueError, TypeError):
item_price = 0
messages.error(request, f"Invalid price for item {p_id}. Setting to 0.")
item_quantity = int(item['qty'])
print(f"Item ID: {p_id}, Quantity: {item_quantity}, Price: {item_price}") # Log each item's details
cart_total_amount += item_quantity * item_price
print("Total Amount Before Discount:", cart_total_amount) # Log total amount before discount
cart_total_amount_decimal = Decimal(str(cart_total_amount))
if request.method == "POST":
coupon_code = request.POST.get("code")
coupon = Coupon.objects.filter(code=coupon_code, active=True).first()
if coupon:
if coupon_code not in request.session.get('applied_coupons', []):
try:
coupon_discount_decimal = Decimal(str(coupon.discount_amount))
coupon_discount_percentage = (coupon_discount_decimal * cart_total_amount_decimal) / 100
except InvalidOperation:
coupon_discount_decimal = Decimal(0)
messages.error(request, "Invalid coupon discount amount.")
request.session['applied_coupons'] = request.session.get('applied_coupons', []) + [coupon_code]
messages.success(request, "Coupon applied successfully!")
else:
messages.warning(request, "Coupon already applied")
else:
messages.warning(request, "Invalid coupon code. Please enter a valid coupon")
cart_total_amount_after_discount = cart_total_amount_decimal - coupon_discount_decimal
print("Total Amount After Discount:", cart_total_amount_after_discount) # Log total amount after discount
return render(request, "core/cart.html", {
"data": request.session['cart_data_obj'],
'totalcartitems': request.session['total_cart_items'],
'cart_total_ammount': cart_total_amount,
'coupon_code': coupon_code,
'coupon_discount': coupon_discount_decimal,
'coupon_discount_percentage': coupon_discount_percentage,
'cart_total_amount_after_discount': cart_total_amount_after_discount
})
else:
messages.warning(request, "Your cart is empty")
return redirect("core:index")
HTML Snippet:
<div class="input-counter">
<span class="input-counter__minus fas fa-minus"></span>
<input id="product-quantity" class="input-counter__text input-counter--text-primary-style" type="number" value="1" data-min="1" data-max="1000">
<span class="input-counter__plus fas fa-plus"></span>
</div>
<div class="button">
<input type="hidden" value="{{p.id}}" class="product-id" name="">
<input type="hidden" value="{{p.title}}" class="product-title" name="">
<input type="hidden" value="{{p.image.url}}" class="product-image" name="">
<input type="hidden" value="{{p.pid}}" class="product-pid" name="">
<button class="btn btn--e-brand-b-2" type="button" id="add-to-cart-btn">Add to Cart</button
</div>
Problem: Despite having products in the cart and prices being displayed correctly in the HTML, the total amount in the cart view is showing as 0. I’ve added logging to track the values, but still, the total amount doesn't seem to be calculated correctly.
Logs indicate that the item_price
might not be picked up correctly, but I can’t pinpoint why. Any insights or suggestions would be greatly appreciated!