Django+ajax (jquery): http 错误代码 403 (禁止)
我正在页面中使用 jquery 开发一个简单的 ajax 调用($.ajax 函数,类型、url 和数据作为选项参数),但出现 403 错误。 因此,我在 $.ajax 函数中添加了 csrf 的进一步选项参数,并且相应的令牌正确显示在模板中。 但我又收到了 403 错误。 我还尝试向视图处理程序(在views.py中)添加一个csrf装饰器,例如@csrf_protect
或@requires_csrf_token
,但没有任何改变。
有帮助吗?
我已经看到这种模式在 django https: //docs.djangoproject.com/en/dev/ref/contrib/csrf/#s-ajax
但对于我来说,进行简单的 ajax 调用确实太多了,所以我找到了一个简短的解决方案
I was developing a simple ajax call ($.ajax function with type, url and data as options parameters) with jquery in a page, but i got 403 error.
So i have added to $.ajax function a further options parameter for csrf, and the corresponding token is correcly displayed in the template.
But i got 403 error again.
I also have tried to add to view handler (in views.py) a csrf decorator, like @csrf_protect
or @requires_csrf_token
but nothing is changed.
Some help?
I have seen this pattern to make an ajax call in django https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#s-ajax
but it is really too much code for me to make a simple ajax call, so i find a short solution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不想对该视图使用 CSRF 保护,则所需的装饰器是
@csrf_exempt
- 其他装饰器将仅确保应用 CSRF 保护。这可能是最简单的解决方案,特别是如果调用对安全性不是特别敏感的话。或者,确保您遵循此处文档中提到的方法: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form
If you don't want to use the CSRF protection for that view, the decorator you want is
@csrf_exempt
--those other will just ensure that the CSRF protection is applied. That's probably the simplest solution, especially if the call isn't particularly security-sensitive.Alternatively, make sure you're following the method mentioned in the docs here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form