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 {% csrf_token %} to the Form}
2. Add the configuration in MIDDLEWARE_CLASSES in Settings: (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 ))