问题翻译:
一般而言,这可以发生时,有一个真正的跨站请求伪造,或当Django的CSRF的机制还没有正确使用。 对于POST表单,您需要确保:
*该视图功能使用模板RequestContext的。
*在模板中,有{%csrf_token%}(模板网址标记在每个邮局形式的内部目标。
*如果您不使用CsrfViewMiddleware,那么你必须在view中使用csrf_protect,
您看到此页面的帮助部分,因为你在settings中设置了 DEBUG = True。 改变这种状况为False,只有最初的错误信息会被显示。您可以使用CSRF_FAILURE_VIEW设置自定义此页面。
解决办法:
1 In the template, there is a {% csrf_token %}
template tag inside each POST form that targets an internal URL.在表单里加上{% csrf_token %}。
2 在setting.py 中设置文件如下:
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', <-------------------新加入 DJANGO <= 1.3 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware' <-------------------新加入 DJANGO 1.4 # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
但是如果在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的功能。
参考:http://www.cnblogs.com/wenjiashe521/archive/2012/08/29/2662041.html