3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I did it. Thank you for the explanation.
How to do this with code example? I succeeded to update the quantity, but not sure how to access the other values.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.