Forbidden (403) CSRF verification failed. Request aborted.

The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. 跨站请求伪造,django 1.4 默认配置了’django.middleware.csrf.CsrfViewMiddleware’,

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
   # 'django.middleware.csrf.CsrfViewMiddleware',#注释掉就正常刘
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

 只需要在每个form标签里面加上{% csrf_token %}即可:

<form action="." method="post">{% csrf_token %}

当然,仅仅这个还不够,还需要:

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

def my_view(request):
    c = {}
    c.update(csrf(request))
    # ... view code here
    return render_to_response("a_template.html", c)






但是如果在1.4版本中加入的话又会出现以下问题:
复制代码
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 219, in __call__
    self.load_middleware()
  File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 51, in load_middleware
    raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
ImproperlyConfigured: Middleware module "django.middleware.csrf" does not define a "CsrfResponseMiddleware" class
Validating models...
复制代码

找不到CsrfResponseMiddleware 这个类:

官方文档是这么说的:

Use of the CsrfResponseMiddleware is not recommended because of the performance hit it imposes, and because of a potential security problem (see below). It can be used as an interim measure until applications have been updated to use the csrf_token tag. It is deprecated and will be removed in Django 1.4.

所以上边第二个新加入的东西要删掉,在template文件中的form中加入tag {% csrf_token %} 如下:

复制代码
<form action="/books/contact/" method="post">
                {% csrf_token %}                             <--------------------------------------新加入的
                <p>Subject: <input type="text" name="subject"></p>
                <p>Your e-mail: (optional): <input type="text" name="email"></p>
                <p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
                <input type="submit" value="Submit">
        </form>
复制代码

加上了之后我运行还是不行:还需要最后一步:在view文件中加入装饰器@csrf_exempt如下:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def contact(request):

问题终于解决掉!!!

因为django之所以引进CSRF是为了避免Cross Site Request Forgeries攻击,而上面的解决方法恰好禁止掉这个django的功能。所以日后还得仔细研究下,在不禁掉这个功能的前提下成功的提交表单。

posted @ 2013-01-10 20:55 Linux、Mongo、Php、Shell、Python、C 阅读(...) 评论(...) 编辑 收藏