此问题可能看似重复,但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.
:
我实施了四颗子弹并收到了同样的错误。我错过了什么?
更新了视图:
@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)
答案 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
。相反,请使用render
。 Source
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)