BUG!!!======> POST方法提交表单的时候 CSRF verification failed. Request aborted. CSRF token missing or incorrect.

时间:2021-09-10 19:16:36
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.

解决方法:

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的功能。所以日后还得仔细研究下,在不禁掉这个功能的前提下成功的提交表单。