django - 由于 CSRF,无法将 jQuery $.post 数据发送到 django 中的 View

标签 django post django-csrf csrf-protection

在发布本文之前,我已经尝试了在线发布的所有解决方案方法,包括 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/

相关文章:

python - Django 完整性错误 _id 可能不为空,外键 id 分配

ios - 如何使用 swift 3 将 base64 编码的图像发布到服务器?

当需要几秒钟才能获取返回的数据时,jQuery .ajax() 在 Safari 中不起作用

python - 使用 request.post 通过 python 发布多部分表单数据不起作用

Django CSRF_COOKIE_DOMAIN - 如何优雅地改变

python - Django:保存腌制对象

python - django orm 组按 json 字段中的 json 键

Python django-admin startproject mysite

jquery - csrf 与 ajax 和 django post

python - Django 上下文处理器和 csrf_token