Код: Выделить всё
$(document).on("click", "#add_button", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url "add_cart" %}",
data: {
product_id: $("#add_button").val(),
csrfmiddlewaretoken: "{{ csrf_token }}",
action: "post",
},
success: function (json) {
{#console.log(json)#}
document.getElementById("cart_quantity").textContent = json.qty
},
error: function (xhr, errmsg, err) {
}
});
})
Код: Выделить всё
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get("cart_key")
if cart is None:
cart = self.session["cart_key"] = {}
self.cart = cart
def add(self, product):
product_id = str(product.id)
if product_id in self.cart:
pass
else:
self.cart[product_id] = {"Price: ": str(product.price)}
self.session.modified = True
def __len__(self):
return len(self.cart)
Код: Выделить всё
def add_cart(request):
cart = Cart(request)
if request.POST.get("action") == "post":
product_id = int(request.POST.get("product_id"))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product)
cart_quantity = cart.__len__()
# response = JsonResponse({"product name: ": product.name})
response = JsonResponse({"qty: ": cart_quantity})
return response
Код: Выделить всё
{{ cart|length }}
введите здесь описание изображения
Подробнее здесь: https://stackoverflow.com/questions/787 ... g-the-page
Мобильная версия