0
votes

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

2 Answers

1
votes

You are missing the return. The view is a function and expects you to return an HTTPResponse object.

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

should be

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

Another thing,

if request.POST

should be

if request.method == 'POST'

Moreover, Avoid using render_to_response. Instead, use render. Source

return render(request, 'list.tpl')
0
votes

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)