【问题标题】:CSRF verification failed despite following documentation尽管有以下文档,但 CSRF 验证失败
【发布时间】:2013-06-20 10:54:32
【问题描述】:

我正在尝试实现一个 ajax 函数,该函数将根据下拉选择的 id 值执行数据库查询。

下拉列表的HTML是

<form method = "POST" action="" >{% csrf_token %}
  <select name = "parentorgs" id = "parentorgs">
    {% for org in parentorg_list %}
      <option value = "{{org.parentorg}}" id = "{{org.parentorg}}" >{{ org.parentorgname }}</option>
    {% endfor %}
  </select>
</form>

一个 jQuery change() 函数用于获取选择的 ID 并将其传递给

function getData(id) {
  $.ajax({
    type : "POST",
    url : "getData/",
    data : {"parentorg" : id},
    datatype: "json",
    success : function(data) {
      console.log(data)
}
  });
}

依次调用视图函数

from django.shortcuts import render_to_response, render
from django.core.context_processors import csrf

def getData(request):
  c = {}
  c.update(csrf(request))
  return render_to_response("app/index.html", c)

Firebug 显示请求是通过 POST 进行的,并且方法 URL 是有效的。另外,该方法的URL已经添加到urls.py中。

此时,它什么也没做,因为我只是想看看方法的响应。该方法旨在执行模型查询并返回结果。

每次在下拉列表中选择一个项目时,我都会收到一个错误 403,描述视图使用 ResponseContext 而不是模板的 Context。

需要做什么来解决这个问题?

【问题讨论】:

  • 如果你输入代码print request.POST会发生什么?
  • @VictorCastilloTorres,我得到了[19/Jun/2013 21:28:11] "POST /app/getData/ HTTP/1.1" 403 2294,它应该是parentorg : 28
  • 你有 js 代码来设置你的 Ajax 查询的标题吗? docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
  • 你必须在你的 Ajax 上设置标题作为上面的评论,也阅读这个 (docs.djangoproject.com/en/1.4/ref/templates/api/…) 并尝试改变它,看看会发生什么from django.template import RequestContextreturn render_to_response("app/index.html", c, context_instance=RequestContext(request))
  • 我更新了我的评论,请再次阅读并尝试这样做:D

标签: django django-csrf


【解决方案1】:

根据doc

如果您使用 Django 的 render_to_response() 快捷方式来使用字典的内容填充模板,则默认情况下您的模板将被传递一个 Context 实例(而不是 RequestContext)。要在模板渲染中使用 RequestContext,请将可选的第三个参数传递给 render_to_response():RequestContext 实例。您的代码可能如下所示:

from django.template import RequestContext 
def getData(request):
  c = {}
  c.update(csrf(request))
  return render_to_response("app/index.html", c, context_instance=RequestContext(request))

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 1970-01-01
    • 2015-08-05
    • 2011-11-18
    • 2014-01-09
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2012-09-08
    相关资源
    最近更新 更多