5

I am submitting a ajax form in django and using

xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));

to get csrf_token. The form is working well in chrome. But in firefox the value of csrf_token is null and its giving 403 forbidden error. I am not receiving csrf_token in console when I checked cookies in console. Why django is not giving csrf_token to firefox browser ?

Ashish Gupta
  • 2,574
  • 2
  • 29
  • 58
  • Did you check `getCookie('csrftoken')` returns any value in Firefox? – Ozgur Vatansever Aug 19 '15 at 21:10
  • Please show the code that is rendering the form. – Alasdair Aug 19 '15 at 21:20
  • form is a ajax form and I am posting serialized data to django with csrftoken that I get from cookie using this `xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))` – Ashish Gupta Aug 19 '15 at 21:27
  • If you look at the network traffic in the browser inspector, do you see the csrf token there? – henrikstroem Aug 19 '15 at 22:02
  • Its behaving weird, when I log in the application , I get csrf_token and then it stays there even after login. But if I clear all the cookies of the browser, then I don't get any csrf_token till I log in . Why I am not getting csrf_token without login ? – Ashish Gupta Aug 19 '15 at 22:44

1 Answers1

5

Add the following decorator to the view that generates the page that holds the form

@ensure_csrf_cookie

From the Django Docs -

Page uses AJAX without any HTML form

A page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent.

Solution: use ensure_csrf_cookie() on the view that sends the page.

Ashish Gupta
  • 2,574
  • 2
  • 29
  • 58
e4c5
  • 52,766
  • 11
  • 101
  • 134