django/ajax CSRF token missing

半城伤御伤魂 提交于 2019-12-31 07:08:41

问题


I have the following ajax function which is giving me a cross site forgery request token error once I get past the minimumlengthinput of 3 with the select2 control. Knowing this I attempted to add { csrfmiddlewaretoken: '{{ csrf_token }}' }, to my data:. After adding the csrfmiddlewaretoken I'm still getting the CSRF token missing or incorrect error. I believe it has something to do with the my function for the searchFilter and searchPage follows. What is the proper way to do this?

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

$(document).ready(function () {
    $('.selectuserlist').select2({
      minimumInputLength: 3,
      allowClear: true,
      placeholder: {
        id: -1,
        text: 'Enter the 3-4 user id.',
      },
      ajax: {
        type: 'POST',
        url: '',
        contentType: 'application/json; charset=utf-8',
        async: false,
        dataType: 'json',
        data: { csrfmiddlewaretoken: csrftoken },

        function(params) {
          return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}";
        },

        processResults: function (res, params) {
            var jsonData = JSON.parse(res.d);
            params.page = params.page || 1;
            var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
            for (i = 0; i < jsonData.length; i++) {
              data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
            }

            return {
              results: data.results,
              pagination: { more: data.more,
              },
            };
          },
      },
    });

  });

My view has the POST method and csrf_token as well.

  {% block content %}
  <form action = "{% url 'multiresult' %}" form method = "POST">
      {% csrf_token %}
  {% block extra_js %}
      {{ block.super }}
      {{ form.media }}

The response from the console is

Forbidden (CSRF token missing or incorrect.): /search/multisearch/ [29/Mar/2018 09:14:52] "POST /search/multisearch/ HTTP/1.1" 403 2502


回答1:


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.




回答2:


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

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



回答3:


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 },


来源:https://stackoverflow.com/questions/49541397/django-ajax-csrf-token-missing

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