Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Real solution</strong></p> <p>Ok, I managed to trace the problem down. It lies in the Javascript (as I suggested below) code.</p> <p>What you need is this:</p> <pre><code>$.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie &amp;&amp; document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i &lt; cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); </code></pre> <p>instead of the code posted in the official docs: <a href="http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax">http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax</a></p> <p>The working code, comes from this Django entry: <a href="http://www.djangoproject.com/weblog/2011/feb/08/security/">http://www.djangoproject.com/weblog/2011/feb/08/security/</a></p> <p>So the general solution is: "use ajaxSetup handler instead of ajaxSend handler". I don't know why it works. But it works for me :)</p> <p><strong>Previous post (without answer)</strong></p> <p>I'm experiencing the same problem actually.</p> <p>It occurs after updating to Django 1.2.5 - there were no errors with AJAX POST requests in Django 1.2.4 (AJAX wasn't protected in any way, but it worked just fine).</p> <p>Just like OP, I have tried the JavaScript snippet posted in Django documentation. I'm using jQuery 1.5. I'm also using the "django.middleware.csrf.CsrfViewMiddleware" middleware.</p> <p>I tried to follow the the middleware code and I know that it fails on this:</p> <pre><code>request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') </code></pre> <p>and then</p> <pre><code>if request_csrf_token != csrf_token: return self._reject(request, REASON_BAD_TOKEN) </code></pre> <p>this "if" is true, because "request_csrf_token" is empty.</p> <p>Basically it means that the header is NOT set. So is there anything wrong with this JS line:</p> <pre><code>xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); </code></pre> <p>?</p> <p>I hope that provided details will help us in resolving the issue :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload