X-CSRFToken Header Resets Session Object

I am using the jQuery code from Django documentation in order to send post requests via ajax. When a link is clicked from a page, it opens another page in a new tab, and at the same time sending an ajax request.

The ajax request, for some reason, is resetting the Session object. The effect is, any new data added in the session (in the non-ajax request) will be lost.

Solution (or rather “workaround”):
After some investigation, the problem lies somewhere in the csrf middleware. I’m still unable to find where the problem is within the middleware, but to patch the issue, I modifed the javascript code to send null X-CSRFToken for non-POST requests. The new code now looks like this:

    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            xhr.setRequestHeader("X-CSRFToken", null);

1 thought on “X-CSRFToken Header Resets Session Object”

  1. This cache backend is usblae, but it might be better to use my drop in replacement for python-memcached, python-ultramemcached . That library is on pypi. You could implement it using the django memcached base class and pass in the new library like so:

Comments are closed.