juntatalor
juntatalor

Reputation: 213

Django csrf in ajax POST (csrf cookie not set until {{csrf}} used)

My django application uses ajax to add an item to shopping cart. The ajax request method is POST, and i enable request header via js:

var csrftoken = getCookie('csrftoken');

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

The problem is, that i send request not from the form, but just using a button and onClick event, so i do not use a {{ csrf }} in the template. So, the cookie is not set, until i visit another page (for example, login page). Should i use a form (it is not a very good idea, because i have many items on one page, and form with csrf token is created for each one), or there is a way to set csrf cookie manually, if it is not set? Thanks.

Upvotes: 0

Views: 1880

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You can always just drop a {% csrf_token %} hidden form field anywhere in your template and pick it up by name if the cookie isn't set yet. You don't have to put it inside a form tag to be valid HTML.

Just change your logic to something like:

var csrftoken == getCookie('csrftoken') || $(":input[name='csrfmiddlewaretoken']").val();

That of course depends on what getCookie returns.

Upvotes: 0

Related Questions