I am using jQuery to do an AJAX POST, but get a CSRF error. I assume this is because the CSRF cookie isn’t sent to the client to send back. Is there a way I can fix this in Django 1.0?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yuji’s suggestion pointed me in the right direction.
I was doing the AJAX POST from a view which was a result of a GET so the Django middleware did not generate any csrf token.
I used the code found in the csrf middleware (/usr/lib/python2.5/site-packages/django/contrib/csrf/middleware.py) to generate a csrf token which I send with the GET context. Now the AJAX POST works fine since the token is present.
To create the csrf token:
In the view context:
Add a hidden input for csrfmiddlewaretoken in the html template.