django/ajax CSRF token missing

南笙酒味 提交于 2019-12-02 08:35:57

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.

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 },
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!