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

作者:我就是个世界 发表于:2011-04-19
settings.py  修改
MIDDLEWARE_CLASSES = ()
在最后加上  
[code]
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
[/code]
也许可能只加第一条就行,如果加两条的话,顺序不可颠倒(CsrfViewMiddleware必须在CsrfResponseMiddleware之前),但是我在lfc的应用中必须两条都加才行。[separator]
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 %} 如:
[code]<form action="{% comment_form_target %}" method="post">{% csrf_token %}[/code]

[b]原因解释:[/b]
[b]CSRF[/b](跨站请求伪造),[url=http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/]django 1.2[/url]以后的版本[url=http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf](django 1.3)[/url]中在projects的setting中默认配置了处理CSRF的中间件
[b]'django.middleware.csrf.CsrfViewMiddleware',[/b]

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

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

所以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
[code]<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a7ad524eaa3c6f536a6afb7b56a40421' /></div>[/code]
这应该是用来让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
版权声明

未经许可,不得转载。