CSRF(跨站请求伪造),django 1.2.1在projects的setting中默认配置了处理CSRF的中间件
'django.middleware.csrf.CsrfViewMiddleware',
因此,如果post提交表单的html代码如下,django会抛出一个异常.
同样在异常信息中,django给出了解决方案.
In the template, there is a
所以html如下,在form区域内加上了{% csrf_token %}
这个标签会自动被django模板处理成一段html
这应该是用来让
CsrfViewMiddleware
中间件进行处理时一个标识吧,这个隐藏域的value看起来是一个32位加密的MD5值。
加上{% csrf_token %}的HTML。
因此,如果post提交表单的html代码如下,django会抛出一个异常.
CSRF token missing or incorrect.
<
form
action
="{%url listenCms:submitComment articleObj.id %}"
method
="post"
>
< div class ="commentTextArea" >
< textarea name ="content" cols ="" rows="" > </textarea>
< input name ="articleId" type ="hidden" value ="`articleObj`.`id`" />
</div>
< input name ="submit" value ="提交评论" type ="submit" />
</form>
< div class ="commentTextArea" >
< textarea name ="content" cols ="" rows="" > </textarea>
< input name ="articleId" type ="hidden" value ="`articleObj`.`id`" />
</div>
< input name ="submit" value ="提交评论" type ="submit" />
</form>
同样在异常信息中,django给出了解决方案.
In the template, there is a
{% csrf_token %}
template tag inside each POST form that targets an internal URL.
所以html如下,在form区域内加上了{% csrf_token %}
这个标签会自动被django模板处理成一段html
<
div
style
='display:none'
>
<
input
type
='hidden'
name
='csrfmiddlewaretoken'
value
='a7ad524eaa3c6f536a6afb7b56a40421'
/>
</div>
加上{% csrf_token %}的HTML。
<
form
action
="{%url listenCms:submitComment articleObj.id %}"
method
="post"
>{% csrf_token %}
< div class ="commentTextArea" >
< textarea name ="content" cols ="" rows="" > </textarea>
< input name ="articleId" type ="hidden" value ="`articleObj`.`id`" />
</div>
< input name ="submit" value ="提交评论" type ="submit" />
</form>
< div class ="commentTextArea" >
< textarea name ="content" cols ="" rows="" > </textarea>
< input name ="articleId" type ="hidden" value ="`articleObj`.`id`" />
</div>
< input name ="submit" value ="提交评论" type ="submit" />
</form>
本文转自阿汐 51CTO博客,原文链接:http://blog.51cto.com/axiii/326306,如需转载请自行联系原作者