Почему я продолжаю получать 403 ошибку в Django после использования csrftoken в Ajax POST вызове?

Я делаю Ajax POST запрос для получения новостных статей. Я поместил csrftoken в заголовки, но все равно продолжаю получать 403 ошибку. Я искал в Интернете и пробовал множество решений, но продолжаю получать 403 ошибку. Почему так происходит?

$('#search-articles').on('submit', function(event) {
      event.preventDefault();
      document.getElementById("loading").style.display = "block";
      document.getElementById("search-bar").style.display = "none";
      document.getElementById("articles").style.display = "none";
      
      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;
      }

      $.ajax({
        url: "{% url 'stocks_sites:get_news_articles' %}",
        type: "POST",
        data: {
          "q": document.getElementById("search-articles").value,
          csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
        },
        headers: {
          "X-CSRFToken": getCookie("csrftoken"),  // don't forget to include the 'getCookie' function
        },
        
        success: function(response) {
          document.getElementById("loading").style.display = "none";
          document.getElementById("search-bar").style.display = "block";
          document.getElementById("articles").style.display = "block";
          $("#search-bar").html(response[0]);             
          $("#articles").html(response[1]);

        }
      })
    })

try

     $.ajax({
        url: "{% url 'stocks_sites:get_news_articles' %}",
        type: "POST",
        data: {
          
          'csrfmiddlewaretoken': document.csrftoken,

        },
        
        
        success: function(response) {
          document.getElementById("loading").style.display = "none";
          document.getElementById("search-bar").style.display = "block";
          document.getElementById("articles").style.display = "block";
          $("#search-bar").html(response[0]);             
          $("#articles").html(response[1]);

        }
      })
    })
Вернуться на верх