問題翻譯:html
通常而言,這能夠發生時,有一個真正的跨站請求僞造,或當Django的CSRF的機制尚未正確使用。 對於POST表單,您須要確保:python
*該視圖功能使用模板RequestContext的。web
*在模板中,有{%csrf_token%}(模板網址標記在每一個郵局形式的內部目標。django
*若是您不使用CsrfViewMiddleware,那麼你必須在view中使用csrf_protect,
session
您看到此頁面的幫助部分,由於你在settings中設置了 DEBUG = True。 改變這種情況爲False,只有最初的錯誤信息會被顯示。您能夠使用CSRF_FAILURE_VIEW設置自定義此頁面。app
解決辦法:python2.7
1 In the template, there is a {% csrf_token %}
template tag inside each POST form that targets an internal URL.在表單里加上{% csrf_token %}。
ide
2 在setting.py 中設置文件以下:post
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版本中加入的話又會出現如下問題:spa
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