django程序报错CSRF verification failed. Request aborted.

时间:2022-09-07 19:34:46

 

django程序的html页面中form的method='post'的时候报错

Forbidden (403) CSRF verification failed. Request aborted.Help Reason given for failure: CSRF token missing or incorrect.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. 
For POST forms, you need to ensure: Your browser is accepting cookies. The view function uses RequestContext for the template, 
instead of Context. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. 
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, 
as well as those that accept the POST data. You're seeing the help section of this page because you have DEBUG = True in your Django settings file.
 Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting.

处理方法可以先屏蔽 修改web2的settings,屏蔽第100行的中间层csrf 97 MIDDLEWARE_CLASSES = (

98 'django.middleware.common.CommonMiddleware',

99 'django.contrib.sessions.middleware.SessionMiddleware',

100 #'django.middleware.csrf.CsrfViewMiddleware',

当然这个方法是不可取的,

先把csrf屏蔽的内容开启 按照上面的提示操作 print req.POST的时候,会看到 [07/Jun/2014 21:15:41] "GET /post_add/ HTTP/1.1" 200 602

<QueryDict:{.........,u'csrfmiddlewaretoken':[u'I5Jwkfkdsjkgjgfgz']}....>

CSRF(Cross-site request forgery跨站请求伪造,也被称为“one click attack”或者session riding,攻击通过在授权用户访问的页面中包含链接或者脚本的方式工作。例如:一个网站用户Bob可能正在浏览聊天论坛,而同时另一个用户Alice也在此论坛中,并且后者刚刚发布了一个具有Bob银行链接的图片消息。设想一下,Alice编写了一个在Bob的银行站点上进行取款的form提交的链接,并将此链接作为图片tag。如果Bob的银行在cookie中保存他的授权信息,并且此cookie没有过期,那么当Bob的浏览器尝试装载图片时将提交这个取款form和他的cookie,这样在没经Bob同意的情况下便授权了这次事务。

风险在于那些通过基于受信任的输入form和对特定行为无需授权的已认证的用户来执行某些行为的web应用。已经通过被保存在用户浏览器中的cookie进行认证的用户将在完全无知的情况下发送HTTP请求到那个信任他的站点,进而进行用户不愿做的行为。

对于初学者来说,解决方案就是提示信息中所提示的添加一个{%csrf_token%},