AJAX 请求和 csrf 令牌

AJAX request and csrf token

所以我想从我的购物车页面向 Django 服务器发送一个 AJAX 请求。它用于更新我的购物车中的商品数量和结帐价格。这是我的 AJAX 请求

$('.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);
    });
  });

这是 django 视图:

@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})

每次我按加号按钮发送请求时,我的服务器控制台都会显示这个。

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

我错过了什么?

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

使用这个,