内容正在载入中,请稍后……
公告
About me
搜索
统计
其他
19 Apr.2011

django 1.3 报错 CSRF token missing or incorrect 解决方法 晴

作者: 我就是个世界   分类:技术&学习 » Django   出处:本站原创            | |
settings.py  修改
MIDDLEWARE_CLASSES = ()
在最后加上  

'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',

也许可能只加第一条就行,如果加两条的话,顺序不可颠倒(CsrfViewMiddleware必须在CsrfResponseMiddleware之前),但是我在lfc的应用中必须两条都加才行。
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before CsrfResponseMiddleware if that is being used, and before any view middleware that assume that CSRF attacks have been dealt with.)
Alternatively, you can use the decorator django.views.decorators.csrf.csrf_protect on particular views you want to protect (see below).

模板里面
form 标签后面  贴上  {% csrf_token %} 如:
<form action="{% comment_form_target %}" method="post">{% csrf_token %}


原因解释:
CSRF(跨站请求伪造),django 1.2以后的版本(django 1.3)中在projects的setting中默认配置了处理CSRF的中间件
'django.middleware.csrf.CsrfViewMiddleware',

因此,如果post提交表单的html代码如下,django会抛出一个异常.
CSRF token missing or incorrect.

同样在异常信息中,django给出了解决方案.
引用
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.


所以html如下,在form区域内加上了{% csrf_token %}
A hidden form field with the name 'csrfmiddlewaretoken' present in all outgoing POST forms. The value of this field is the value of the CSRF cookie.
This part is done by the template tag (and with the legacy method, it is done by CsrfResponseMiddleware).
这个标签会自动被django模板处理成一段html
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a7ad524eaa3c6f536a6afb7b56a40421' /></div>

这应该是用来让CsrfViewMiddleware 中间件进行处理时一个标识吧,这个隐藏域的value看起来是一个32位加密的MD5值。

参考:
django 1.2.1更新后 关于CSRF token missing or incorrect的问题
       http://axiii.blog.51cto.com/396236/326306
This document describes Django 1.2. For development docs,  
       http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/
This document is for Django's development version, which can be significantly different from previous releases. Get older docs here: 1.3, 1.2, 1.1, 1.0  
       http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf
分享到QQ空间
时间:16:00 评论(0) 引用(0) 阅读(6979) Tags: , , ,
发表评论
  昵称 [注册]
  密码 (游客无需密码)
  网址
  电邮
OpenID登入 权限选项 表情