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?
-
3Add the token manually to the ajax post parameters - that's the easiest way. I forget where exactly the token generation function is for 1.0 (csrf has moved a lot since 1.0) but it shouldn't be hard to find! For example with 1.3, RequestContext automatically has a variable called `csrf_token` which is the token string (not to be confused with the tag). – Yuji 'Tomita' Tomita Mar 28 '12 at 00:17
-
possible duplicate of [Django CSRF check failing with an Ajax POST request](http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request) – Burhan Khalid Mar 28 '12 at 06:14
-
This can't be Django 1.0, which didn't have CSRF protection. – Daniel Roseman Mar 28 '12 at 06:52
-
django.VERSION tells me I am using 1.0.2 and the reference at https://docs.djangoproject.com/en/1.0/ref/contrib/csrf/ describes how to use CSRF protection in Django 1.0. – Mitch Mar 29 '12 at 00:31
2 Answers
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:
def csrf_token_create(request):
from django.contrib.csrf.middleware import _make_token
try:
session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
except KeyError:
# No session, no check required
return None
csrf_token = _make_token(session_id)
return csrf_token
In the view context:
csrf_token = csrf_token_create(request)
return render_to_response('view.html', {'csrfmiddlewaretoken': csrf_token})
Add a hidden input for csrfmiddlewaretoken in the html template.

- 2,350
- 7
- 29
- 48
-
When you are able to, accept this as the correct answer. If you have any code that might be useful for people in the future you should edit your post and include it if you can :) – Timmy O'Mahony Mar 28 '12 at 01:57
Documentation for django 1.4 has the code for you. https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/
I probably think this would also work for django 1.0 because what you have to do with the code is basically just adding the jquery function to any js file your page loads. For version 1.4, we have to add {% csrf_token %} tag inside the form element in django template.. Try this!

- 2,145
- 23
- 28