The following error occurs when submitting a post form using DJANGO:
Forbidden (403)CSRF verification failed. Request aborted.
The reason has been clearly stated in "help.
In general, this can happen when there is a real cross-site request forgery, or when Django's csrf mechanism is not properly used. For the post form, make sure that:
* This view function uses the template requestcontext.
* In the template, there are {% csrf_token %} (the template URL is marked as an internal target in the form of each post office.
* If you do not use csrfviewmiddleware, you must use csrf_protect in the view,
You can see the help section on this page because you have set DEBUG = true in settings. If this condition is changed to false, only the initial error information is displayed. You can use csrf_failure_view to customize this page.
Therefore, the solution is as follows:
1. Add in Form{% csrf_token %}
2. In settingsAdd the middleware_classes configuration: (usually by default)
'django.middleware.csrf.CsrfViewMiddleware',
#'django.middleware.csrf.CsrfResponseMiddleware',
1.2.x example:
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',)
3. Add the @ csrf_protect annotation to the method in the view. Use requestcontext instead of context. Example:
Certificate ----------------------------------------------------------------------------------------------------------------------------------
@ Csrf_protect
Def login (request ):
...
Return render_to_response('index.html ', context_instance = requestcontext (request ))
Certificate ----------------------------------------------------------------------------------------------------------------------------------
Details:
Https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/
Https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf
Additional reading:
Django. contrib. csrfThe Development Kit has only one module:Middleware. py. This module contains a Django middleware class --CsrfmiddlewareThis class implements the csrf protection function.
In the settings file'Django. contrib. csrf. Middleware. csrfmiddleware'AddMiddleware_classesEnable csrf protection. The middleware must be inSessionmiddleware AfterExecution, so in the listCsrfmiddlewareMust appear inSessionmiddleware Before(Because the response middleware is executed from the back to the Front ). At the same time, it must process the response results before the response is compressed or decompressed. ThereforeCsrfmiddlewareMust be inGzipmiddlewareThen run. Once addedMiddleware_classesSetting.