Getting an error const request = new Request( /* URL */, {headers: {'X-CSRFToken': csrftoken}} ); fetch(request, { method: 'POST', mode: 'same-origin' // Do not send CSRF token to another domain. }).then(function(response) { // ... });

I’m trying to build an add to card form with AJAX and I get this error when I click the add to cart button


Forbidden (CSRF token from POST has incorrect length.): /inventory/product/
this-is-a-test-product/{% url "inventory:single_product_add_to_cart" %}
[05/Sep/2023 01:18:23] "POST /inventory/product/this-is-a-test-product/%7B%
%20url%20%22inventory:single_product_add_to_cart%22%20%%7D HTTP/1.1" 403 25


    <form action="{% url 'inventory:single_product_add_to_cart' %}" method="POST">
            <label for="select">Qty</label>
            <select id="select" class="h6 store-select-dropdown">

                {% for i in gogo %}
                      <option value="{{i}}">{{i}}</option>
                {% endfor %}

      <button type="button" class="" value="{{}}" id="add_button">Dropship</button>



$(document).on('click','#add_button', function(e){

			url: '{% url "inventory:single_product_add_to_cart" %}',
			data: {
				productid: $('#add_button').val(),
				productqty: $('#select option:selected').text(),
				csrfmiddlewaretoken: '{{csrf_token}}',
				action: 'post'

			error: function (xhr, errmsg, err){}



Any idea what causes this or how to fix?

Thanks in advance

It’s because CSRF is to be sent with your post request, from the official docs you can see how to send CSRF with AJAX How to use Django’s CSRF protection | Django documentation | Django