【发布时间】:2014-10-01 18:03:13
【问题描述】:
首先我去localhost:8000看到如下页面:
</div>
< form id="SignUpForm" name="form_signupform" method="post" action="hello/" >
{% csrf_token %}
< fieldset class="roundedCorners" style = "display: table;" >
< legend align="center"><em>Sign Up</em></legend>
< p></p>
< p style="display: block;">
etc.
在 localhost:8000 上面的页面视图是使用views.py中的函数提供的:
def login(request):
c = {}
c = {'query': 'abcd.com'}
response = render_to_response('index.html', c,context_instance=RequestContext(request))
return response
在这里,在提供的页面源中,我可以看到如下 csrf 值:
< form id="SignUpForm" name="form_signupform" method="post" action="hello/" >
< input type='hidden' name='csrfmiddlewaretoken'
value='rjbU4k8DY3EEBWVhlsgIYU3gEu4x3ctM' / >
< fieldset class="roundedCorners" style = "display: table;" >
< legend align="center"><em>Sign Up</em></legend>
< p >< /p >
< p style="display: block;">
etc.
按下提交按钮时会调用另一个视图。在views.py:
def hello(request):
if request.method == "POST":
return HttpResponseRedirect("genResp1.html")
else:
return HttpResponseRedirect("genResp2.html")
但是,在按下提交按钮时,我收到以下错误:
Forbidden (403)
CSRF verification failed. Request aborted.
...
...
Help
Reason given for failure:
CSRF cookie not set.
:: 我已经咨询过 a) django docs,b) stackoverflow.com,c) google 等。我已经尝试了所有可能的代码排列组合......但错误从未改变......(我可以设置cookie 调用 set_cookie 函数...可以正常工作...但是无法设置 csrf cookie...为什么?)请不要搜索网络并编写解决方案。我已经搜索了过去 6 天。我尝试了所有形式的视图功能。其中之一在上面给出。如果您自己完成了 CSRF 工作并让它运行,那么请写下您是如何做到的......(我使用 python 3.4 和 django 1.7)
【问题讨论】:
-
在发出
POST请求时,您是否也在发送 csrf 令牌? -
我不明白你的解决方案......我认为它足以使用请求竞赛......你能帮我写几行代码吗?
-
嗯,你指出的是使用 javascript 和 ajax ......但我想知道使用 html5 和内置 django 函数的解决方案......你知道如何将该令牌发送回重定向表单?
-
使用开发者工具可以检查浏览器是否设置了csrf cookie或cookie被禁用。