Search code examples
djangodjango-csrf

Django 1.6 "CSRF verification failed. Request aborted."


This question may seem like a duplicate but none of the solutions on Google/SO are working, so please do not mark as duplicate.

Here is my view code:

@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)

Here is the login template:

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

When I submit the POST request from the form I get CSRF cookie not set.:

enter image description here

I've implemented the four bullets and received the same exact error. What am I missing?

Updated view:

@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)

Solution

  • I fixed this issue by using RequestContext instead of 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)