由于CSRF无法将jQuery $ .post数据发送到Django中的视图

问题描述:

在发布此内容之前,我尝试过在线发布的每种解决方案方法,包括Stackoverflow和Django的解决方案. (我认为出错的原因可能是由于我使用的是jQuery和django的较新版本,并且大多数解决方案都已过时,使用jQuery 1.9和django 1.5.1)

Before posting this i've tried every solution method posted online, including solutions on Stackoverflow and Django. (I think the reason for error perhaps is due to the fact that i'm on a newer verison of jQuery and django and most solutions are dated, using jQuery 1.9 and django 1.5.1)

以下是无法使用的解决方案的网址:

Here are some URL's to solutions that don't work:

Django CSRF检查失败,并带有Ajax POST请求

如何在django中使用$ .post?

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

任何帮助将不胜感激.另一种可能的错误是我实际上不确定这些片段的确切位置.到目前为止,我已经在文档加载时将所有内容粘贴到了jquery中,我还尝试将代码粘贴到.js文件的最开始. (我的javascript代码分为几部分,有些是独立的.js文件,有些则与django上下文渲染的html内联,因此任何带有"{{csrftoken}}"的解决方案都是不好的.

Any help would be appreciated. Another possibility for error is the fact that i'm not actually sure where to place these snippets exactly. So far i've pasted everything inside the jquery on document load, i've also tried pasting the code in the very start of the .js file. (My javascript code is fragmented in chunks, some are seperate .js files and some are inline with the html being rendered with django context, so any solutions with "{{ csrftoken }}" are bad.

谢谢!

仅当模板中存在CSRF令牌或使用ensure_csrf_cookie()装饰视图时,CSRF令牌才会被设置.将{% csrf_token %}放在index.html中将使其适用于您的所有页面.

The CSRF token only gets set if it's present in the template or if the view is decorated with ensure_csrf_cookie(). Putting {% csrf_token %} in index.html will make it apply for all your pages.

文档:

CSRF令牌也存在于DOM中,但前提是使用模板中的csrf_token明确包含了CSRF令牌.

The CSRF token is also present in the DOM, but only if explicitly included using csrf_token in a template.

...

如果您的视图未呈现包含csrf_token模板标记的模板,则Django可能未设置CSRF令牌cookie.在将表单动态添加到页面的情况下,这很常见.为了解决这种情况,Django提供了一个视图装饰器来强制设置cookie:sure_csrf_cookie().

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().