Firefox 未收到 django csrf_token

Ash*_*pta 5 python django firefox django-csrf

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

xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
Run Code Online (Sandbox Code Playgroud)

获取 csrf_token。该表单在 chrome 中运行良好。但是在 Firefox 中, csrf_token 的值为 null 并且给出了 403 禁止错误。当我在控制台中检查 cookie 时,我没有在控制台中收到 csrf_token。为什么 django 没有将 csrf_token 提供给 firefox 浏览器?

e4c*_*4c5 5

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

@ensure_csrf_cookie

来自 Django 文档 -

页面使用 AJAX,没有任何 HTML 表单

页面通过 AJAX 发出 POST 请求,并且该页面没有带有 csrf_token 的 HTML 表单,这会导致发送所需的 CSRF cookie。

解决方案:在发送页面的视图上使用ensure_csrf_cookie()。