I keep getting 403 Errors from Django.
I set up my settings.py to use the CSRF protection, and used the csrf_token token in my template.
Here is the JS file I included just after the HTML header: http://bpaste.net/show/87791/
Using Firebug I can check that the CSRF cookie is there. Later on the page, the user clicks on a button that triggers this code:
myFunction: function() {
$.ajax({
type: 'POST',
url: window.localtion.href + 'myajaxview',
async: false
});
}
I am using a simple class based view inheriting from TemplateView to display this page. 'myajaxview' is inheriting from View and a JSON Mixin. However its code is never executed since django cannot validate the CSRF token.
It seems to me that the ajax doesn't send the token with the POST headers as it should. Or am I missing something?
EDIT: I moved the $.ajaxSetup call just before the call to the $.ajax() POST function and it worked. I tried to move it somewhere else and it failed. The problem is more related to Ajax than Django I think. So, my question is still there, I don't want to put the $.ajaxSetup call before each $.ajax call, I don't think it is the way things are done, I don't want to repeat myself. So this was just a workaround and I am asking for the solution.
Thank you for your help. The answer is really nasty, I found it out by beginning with a simple example to test ajaxSetup + ajax and then I added more complexity to match my original code.
It was because of jquery-tools. When I began using bootstrap-twitter I saw that they advise to put javascript includes at the end of the page. So I put the jquery-tools.js include there as well. Little did I know that in this script file a call to $.ajaxSetup was made which overrode my own.
The solution is to put the jquery tools include at the top level. However at this point I am not sure how much it will conflict with my code. Since I need the ajaxSetup for each ajax request I will do.
It took me a day to find out, I was on #jquery and #django and a lot of people went out of their way to try to find out the solution. If you ever get a complex code base that you cannot share and a problem you want to solve here's my advice: try to make the simplest example working and change it until it matches your failing setup. It will save everybody's time, above all your own.