[Django]-Django/ajax CSRF token missing

12👍

You have to include the csrf_token as header:

var csrftoken = $("[name=csrfmiddlewaretoken]").val();

//example ajax
$.ajax({
    url: url,
    type: 'POST',
    headers:{
        "X-CSRFToken": csrftoken
    },
    data: data,
    cache: true,
});

Also make sure that CSRF_COOKIE_SECURE = False if you’re not on ssl.
If you’re using ssl set it to True.

Whether to use a secure cookie for the CSRF cookie. If this is set to True, the cookie will be marked as “secure,” which means browsers may ensure that the cookie is only sent with an HTTPS connection.

3👍

A mixture of JS and Django template language helped solve this.

  $.ajax({
         type: 'POST',
         headers:{
        "X-CSRFToken": '{{ csrf_token }}'
         }
  })

1👍

Just changed the line of code below, it is much simpler because you don’t have to involve the template. The js snippet you provided already has the csrf value.

  data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
      // INTO
  data: { csrfmiddlewaretoken: csrftoken },
👤Du D.

Leave a comment