Firefox 没有收到 django csrf_token

Firefox not receiving django csrf_token

我正在 Django 中提交 ajax 表单并使用

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

得到csrf_token。该表格在 chrome 中运行良好。但是在 firefox 中 csrf_token 的值是 null 并且它给出了 403 forbidden 错误。当我在控制台中检查 cookie 时,我没有在控制台中收到 csrf_token。为什么 django 不给 firefox 浏览器 csrf_token?

将以下装饰器添加到生成包含表单的页面的视图中

@ensure_csrf_cookie

来自 Django 文档 -

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.