简体   繁体   English

使用django 1.10.5的Ajax发布请求错误

[英]Ajax Post Request Error using django 1.10.5

Over the last week or so I have been struggling to successfully implement a jQuery ajax request to pass data from a javascript function within my annualgoals.html to a django view in order to save data to my database. 在过去一周左右的时间里,我一直在努力成功实现一个jQuery ajax请求,将我的annualgoals.html中的javascript函数数据传递到django视图,以便将数据保存到我的数据库中。 Currently I am just trying to test the data transfer by printing the data on the django end. 目前我只是试图通过在django端打印数据来测试数据传输。

I have already checked out the following threads but cannot see any that show the same error as I can see (I am almost certainly missing something obvious). 我已经检查了以下线程,但看不到任何显示相同的错误,我可以看到(我几乎肯定错过了一些明显的东西)。

Forbidden (CSRF token missing or incorrect) Django error 禁止(CSRF令牌丢失或不正确)Django错误

"CSRF token missing or incorrect" while post parameter via AJAX in Django “CSRF令牌丢失或不正确”,同时在Django中通过AJAX发布参数

While a missing CSRF token was my first problem, the answers on StackOverflow and the django docs do a good job of explaining what must be done to ensure the csrf token is included. 虽然缺少CSRF令牌是我的第一个问题,但StackOverflow和django文档上的答案很好地解释了为确保包含csrf令牌必须采取的措施。 However, when following the recommended steps I receive the following django error: 但是,按照建议的步骤,我收到以下django错误:

response.set_cookie(settings.CSRF_COOKIE_NAME, AttributeError: 'NoneType' object has no attribute 'set_cookie' response.set_cookie(settings.CSRF_COOKIE_NAME,AttributeError:'NoneType'对象没有属性'set_cookie'

My code is as follows: 我的代码如下:

annualgoals.html annualgoals.html

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

function csrfSafeMethod(method) {
          // these HTTP methods do not require CSRF protection
          return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }

var data = [1, 2, 3, 4]
var csrftoken = getCookie('csrftoken');

// Ajax Setup

    $.ajaxSetup({
       beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
          }
    });

 // Ajax Call

    $.ajax({
      type: 'POST',
      url: "{% url 'LifeAdmin:saveAnnualGoals' %}",
      data: {'data[]': data},
    });

views.py views.py

@ensure_csrf_cookie
@login_required
def saveAnnualGoals(request):
   if request.method == 'POST':
       data = request.POST.get('data')
   print(data)

urls.py urls.py

url(r'^saveAnnualGoals$', views.saveAnnualGoals, name='saveAnnualGoals')

I am using Django 1.10.5 and Python 3.6.1 我正在使用Django 1.10.5和Python 3.6.1

Any help would be greatly appreciated!! 任何帮助将不胜感激!!

Thanks :) 谢谢 :)

Your view needs to return a Response. 您的视图需要返回响应。 With your actual code, the view returns nothing, so None . 使用实际代码,视图不返回任何内容,因此None Django then tries to add the cookie to the Response but as it is None, you get the error message you posted. Django然后尝试将cookie添加到响应,但由于它是None,您将收到您发布的错误消息。

Example: 例:

return HttpResponse(status=200)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM