“CSRF verification failed. Request aborted. CSRF token missing or incorrect.” with Django and YUI
September 30th, 2011
So if you have a piece of YUI Javascript code similar to the one shown below
function foo() { var on_success = function(o) { alert('Yay!'); }; var on_failure = function(o) { alert('Oh ones!') } var callback = { success: on_success, failure: on_failure, }; var url = '/url/to/invoke'; var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback); } |
and the URL the AJAX call invokes returns the “CSRF verification failed. Request aborted. CSRF token missing or incorrect.” error, the easiest way to properly handle is to set the custom X-CSRFToken HTTP header to the same value the csrftoken cookie has been set by Django to, just like the Django documentation says it can be done.
In code terms, that will do the trick
function foo() { var on_success = function(o) { alert('Yay!'); }; var on_failure = function(o) { alert('Oh ones!') } var callback = { success: on_success, failure: on_failure, }; var url = '/url/to/invoke'; YAHOO.util.Connect.initHeader('X-CSRFToken', YAHOO.util.Cookie.get('csrftoken')); var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback); } |
Hoping this helps someone some day!
