Search code examples
pythondjangofirefoxdjango-csrf

Firefox not receiving django csrf_token


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 ?


Solution

  • 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.