Django 1.6" CSRF验证失败。请求已中止。"

时间:2014-06-05 16:58:55

标签: django django-csrf

此问题可能看似重复,但Google / SO上的解决方案均无效,因此请勿将其标记为重复。

这是我的观看代码:

@csrf_protect
def login(request):
  if request.POST:
    render_to_response('list.tpl', context_instance=RequestContext(request))
  else:
    # Prepare templates
    header = get_template("header.tpl")
    body = get_template("login.tpl")
    footer = get_template("footer.tpl")

    html = header.render(Context({"title": "Login", "charset": "UTF-8"}))
    html = html + body.render(Context({}))
    html = html + footer.render(Context({}))

    return HttpResponse(html)

以下是登录模板:

<body>
  <div class="bodydiv">
    <h3>Login</hd>
    <form id="login" method="post" action=".">{% csrf_token %}
      User: <input type="text" name="user"><br>
      Password: <input type="password" name="password">
      <input type="submit" name="submit_login" value="Login">
    </form>
  </div>
</body>

当我从表单提交POST请求时,我得到CSRF cookie not set.

enter image description here

我实施了四颗子弹并收到了同样的错误。我错过了什么?

更新了视图:

@csrf_protect
def login(request):
  print("Method: " + request.method)

  if request.method == "POST":
    print("IN POST!")
    return render(request, 'list.tpl', {})
  elif request.method == "GET":
    print("IN GET!")
    # Prepare templates
    header = get_template("header.tpl")
    body = get_template("login.tpl")
    footer = get_template("footer.tpl")

    html = header.render(Context({"title": "Login", "charset": "UTF-8"}))
    html = html + body.render(Context({}))
    html = html + footer.render(Context({}))

    return HttpResponse(html)

2 个答案:

答案 0 :(得分:1)

您错过了return。视图是一个函数,希望您返回一个HTTPResponse对象。

render_to_response('list.tpl', context_instance=RequestContext(request))

应该是

return render_to_response('list.tpl', context_instance=RequestContext(request))

另一件事,

if request.POST

应该是

if request.method == 'POST'

此外,避免使用render_to_response。相反,请使用renderSource

return render(request, 'list.tpl')

答案 1 :(得分:0)

我使用RequestContext代替Context修复此问题:

def login(request):
  if request.method == "POST":
    return render(request, 'login.tpl')
  elif request.method == "GET":
    # Prepare templates
    header = get_template("header.tpl")
    body = get_template("login.tpl")
    footer = get_template("footer.tpl")

    html = header.render(RequestContext(request, {"title": "Login", "charset": "UTF-8"}))
    html = html + body.render(RequestContext(request, {}))
    html = html + footer.render(Context({}))

    return HttpResponse(html)