Reputation: 57
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.
Upvotes: 3
Views: 4498
Reputation: 16309
I think you have a bit of a misconception about how your django application communicates with your client. You have to understand the request response lifecycle.
Your template context does only exist inside the request response lifecycle. Every request from your client will start a new worker with a new template context to generate a response. There is no persistent stateful connection between your client application and django.
That means that if you want to update your client side page without reloading it (requesting it again) you have to pass the new card count with your JsonResponse
to the client and let the javascript code that handles the response update the displayed value.
Upvotes: 3
Reputation: 527
You can not. Once the page have been rendered, all template variables disappear. You can use an input hidden
to store the cart.count
value, and then update that value.
Upvotes: 2