【问题标题】:Jquery $post request is not working in DjangoJquery $post 请求在 Django 中不起作用
【发布时间】:2012-12-29 09:13:23
【问题描述】:

我正在尝试使用来自 javascript 的 $post 请求到我的 django 模板中,但是我缺少一些东西,因为它不起作用。

我会告诉你我的代码:

这是模板:

//TEMPLATE
//This code will send a string to django "views.py" file,
//then it will show a pop up message from the data retreived from "views.py"

function test_post(){ 
   $.post("/xhr_test", 
      {name: "Monty", food: "Spam", csrftoken : "{{ csrf_token }}" },

      function(data) {
          alert(data)
      ;}); 
};

这是views.py:

// VIEWS.PY
//Depending on the type of request it will send a message or another.


def xhr_test(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            message = "This is an XHR POST request"
            # Here we can access the POST data
            print request.POST
    else:
        message = "No XHR"
    return HttpResponse(message)

此代码未按应有的方式显示“这是一个 XHR POST 请求”消息。但是,当使用 $get 请求时,它会显示“这是一个 XHR GET 请求”消息。

thread 中也有类似的疑问。即使我使用了那里提供的答案,代码也不起作用。

我猜答案一定与“{{ csrf_token }}”有关,但不确定如何...

我们将不胜感激任何类型的帮助。

【问题讨论】:

  • 你如何填充csrf_token

标签: jquery django post get


【解决方案1】:

如果这是由于 csrf 令牌(您可以使用 firebug 在浏览器中检查),则在您的 views.py 中使用它

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def xhr_test(request):
   ...........

【讨论】:

  • 为什么要禁用 csrf 保护?
  • 每当我们在模板中使用 ajax 或 jquery 时,即使我们正在使用中间件,我们通常也会收到 csrf 令牌的错误,因此这是检查天气的一种方法是否存在另一个错误或只是 csrf 丢失错误.我不是强迫任何人使用它,只是为了测试目的。
  • 显然 Inforian 告诉我使用“csrf_exempt”进行调试。我从来没有听说过firedebug,它真的很有帮助。它与@csrf_exempt 一起使用。然而,并非没有它。我会仔细阅读 firebug 告诉我的建议,我会告诉你的。
【解决方案2】:

如果您遵循使用 django.middleware.csrf.CsrfViewMiddleware 的默认方式,则 csrf 令牌的正确发布密钥是 csrfmiddlewaretoken

但是,您应该查看 CSRF docs 中的 AJAX 部分。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    相关资源
    最近更新 更多