Skip to content Skip to sidebar Skip to footer

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'); $.aja

Solution 1:

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.

Post a Comment for "Django Csrf In Ajax Post (csrf Cookie Not Set Until {{csrf}} Used)"