Ajax CSRF problem in Django 1.3

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

http://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax http://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax

Answers

When there is no form on a page that is already using {% csrf_token %}, the cookie will not be sent. Therefore, as you noted, you will get an error when you attempt to use Ajax on such a page. This will lead to erratic behavior if you have a site with a mix of pages with various combinations of forms and ajax posts.

https://code.djangoproject.com/ticket/15354 https://code.djangoproject.com/ticket/15354

The solution in the patch, will should roll out with 1.3.1, is the ensure_cookie_csrf decorator. That decorator does not exist in 1.3 or 1.2.5

No need to wait, however. Just add this line to any view which contains AJAX posts a CSRF form:

request.META["CSRF_COOKIE_USED"] = True

Example:

def calculator(request):
    request.META["CSRF_COOKIE_USED"] = True
    return render_to_response( calc.html , { form : CalcForm()})

FYI - this is exactly what that decorator does.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/5499597/ajax-csrf-problem-in-django-1-3

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils