AJAX request and csrf token

640 views Asked by At

So from my cart page I want to rend an AJAX request to Django server. It is made to update the number of items in my cart and the checkout price. Here is my AJAX request

$('.plus').click(function() {

    var productId = $(this).find('#productId').val();
  
    req = $.ajax({
      headers: { "X-CSRFToken": csrftoken },
      url: 'updateit/',
      type: 'post',
      data: {'productId' : productId,
              'action' : 'plus'}
    });

    req.done(function(data) {
      $('#total').text(data.total);
      $('#total_with_delivey').text(data.total_with_delivery);
      $('#summary').text(data.subtotal);
    });
  });

Here is django view:

@require_http_methods(["POST"])
def updateit(request):
    product = Product.objects.get(id = request.POST['productId'])
    action = request.POST['action']

    if action == 'plus':
        try:
            cart = Cart.objects.get(cart_id=_cart_id(request))
        except Cart.DoesNotExist:
            cart = Cart.objects.create(
                cart_id = _cart_id(request)
                )
            cart.save()
        try:
            cart_item = CartItem.objects.get(product=product, cart=cart)
            if cart_item.quantity < cart_item.product.stock:
                cart_item.quantity += 1
            cart_item.save()
        except CartItem.DoesNotExist:
            cart_item = CartItem.objects.create(
                product = product,
                quantity = 1,
                cart = cart
                )
            cart_item.save()
    elif action == 'minus':
        if cart_item.quantity > 1:
            cart_item.quantity -= 1
            cart_item.save()
        else:
            cart_item.delete()

    item_count = 0
    total = 0
    cart = Cart.objects.filter(cart_id=_cart_id(request))
    cart_items = CartItem.objects.all().filter(cart=cart[:1])
    cart_item = CartItem.objects.get(id=request.POST['productId'])
    subtotal = cart_item.quantity*cart_item.price
    
    for cart_item in cart_items:
        total += (cart_item.product.price * cart_item.quantity)
        item_count += cart_item.quantity

    total_with_delivery = total + 50


    return JsonResponse({'result' : 'success', 'item_count' : item_count, 'total' : total, 'total_with_delivery' : total_with_delivery, 'subtotal' : subtotal})

Every time I press a plus button to send the request my server console shows me this.

> Forbidden (CSRF token missing or incorrect.): /updateit/ [14/Oct/2020
> 18:36:10] "POST /updateit/ HTTP/1.1" 403 2555

What am I missing?

1

There are 1 answers

3
Exprator On BEST ANSWER
req = $.ajax({
      url: 'updateit/',
      type: 'post',
      data: {
              'productId' : productId,
              'action' : 'plus',
              csrfmiddlewaretoken:'{{ csrf_token }}',
            }
    });

use this,