Solve the Problem of CSRF verification failed. Request aborted. In django Development

Source: Internet
Author: User

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 ))


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.