在发布本文之前,我已经尝试了在线发布的所有解决方案方法,包括 Stackoverflow 和 Django 上的解决方案。 (我认为错误的原因可能是由于我使用的是较新版本的 jQuery 和 django,并且大多数解决方案都已过时,使用 jQuery 1.9 和 django 1.5.1)
以下是一些不起作用的解决方案的 URL:
Django CSRF check failing with an Ajax POST request
How to use $.post with django?
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
如有任何帮助,我们将不胜感激。错误的另一种可能性是我实际上不确定将这些片段准确放置在哪里。到目前为止,我已将所有内容粘贴到文档加载时的 jquery 中,我还尝试将代码粘贴到 .js 文件的最开头。 (我的 javascript 代码是碎片化的,有些是单独的 .js 文件,有些与使用 django 上下文渲染的 html 内联,因此任何带有“{{ csrftoken }}”的解决方案都是不好的。
谢谢!!
最佳答案
只有在模板中存在 CSRF token 或者 View 使用 ensure_csrf_cookie()
修饰时,才会设置 CSRF token 。将 {% csrf_token %}
放入 index.html
中将使其适用于您的所有页面。
来自docs :
The CSRF token is also present in the DOM, but only if explicitly included using csrf_token in a template.
...
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().
关于django - 由于 CSRF,无法将 jQuery $.post 数据发送到 django 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094462/