This context processor
def cart_proc(request):
return (dict(cart=Cart(request)))
gives me variable {{cart}} in my template, so I can use {{ cart.count }} in base.html.
count is method that count amount of products in cart.
This is my js
function addProduct(){
$('form.add-product').on('submit', function(){
var link = $(this)
var quantity = $(this).find('#id_quantity').val()
$.ajax({
'url': link.attr('action'),
'type': 'POST',
'dataType': 'json',
'data': {
'quantity': quantity,
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
},
'success': function(data, status, xhr){
alert('Success');
return false;
},
'error': function(xhr, status, error){
alert('Error on server. Please try again later.');
return false;
}
});
return false;
});
}
And my view (I use django-cart for my cart)
def add_to_cart(request, id):
form = QuantityForm(request.POST)
if form.is_valid():
product = Product.objects.get(id=id)
quantity = request.POST['quantity']
cart = Cart(request)
cart.add(product, product.price, quantity)
return JsonResponse({'status': 'success'})
I want to update {{cart.count}} when I add product in cart with AJAX, without page reloading. Now it updating only after reloading.