Django的CSRF令牌没有形式 [英] Django CSRF Token without forms

查看:128
本文介绍了Django的CSRF令牌没有形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来很奇怪,但怎么样的情况下,无需使用形式发布的内容的JavaScript(例如AJAX)(也可能读取从表面几个内容)。

Sounds strange but what about the scenario posting contents with Javascript (for example AJAX) without using a form (could be possible to read several contents from the surface).

我应该在哪里放置csrf_token模板标签?我已经添加了AJAX修复: <一href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax">https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Where should I place the csrf_token template tag? I already added the AJAX Fix: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

...但我得到的CSRF验证失败。请求中止。 404错误。

...but I get the "CSRF verification failed. Request aborted." 404 Error.

推荐答案

您必须设置一个自定义HTTP标头, X-CSRFToken ,在你的AJAX请求。参见:<一href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax">https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

You must set a custom HTTP header, X-CSRFToken, in your AJAX request. See: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

如果你已经遵循这个建议,应该工作。使用类似Firebug的,以监视正在被发送的请求,并检查头,以确保自定义标题是真正被传递。如果不是,那么再次检查您的实现,以确保你没有它就像文档描述了。

If you've already followed that advice, it should be working. Use something like Firebug to monitor the request that's being sent and inspect the headers to ensure that the custom header is truly being passed. If it's not, then check your implementation again to make sure you did it just as the docs describe.

另外请注意:

由于jQuery的1.5引入了一个错误,上面的例子将不会正确的版本工作。确保您至少运行的jQuery 1.5.1。

Due to a bug introduced in jQuery 1.5, the example above will not work correctly on that version. Make sure you are running at least jQuery 1.5.1.

这篇关于Django的CSRF令牌没有形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆