Django中使用Ajax请求没有表单元素 [英] Using ajax request in Django without form element

查看:183
本文介绍了Django中使用Ajax请求没有表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发出一个Ajax请求(通过jQuery,但我认为这是无关紧要在这种情况下),而在Django使用表单元素。按照文档,我应该能够做到这一点,通过使用 ensure_csrf_cookie 装饰,不过,我得到错误:无法导入名称ensure_csrf_cookie

I'd like to send an ajax request (via Jquery, although I think that's irrelevant in this situation) without using a form element in Django. According to the documentation, I should be able to do that by using the ensure_csrf_cookie decorator, however, I get Error was: cannot import name ensure_csrf_cookie.

我用下面的导入从django.views.decorators.csrf进口ensure_csrf_cookie

我没有找到大量的文档约<$​​ C $ C> ensure_csrf_cookie ,所以任何帮助将大大AP preciated。

I didn't find a great deal of documentation about ensure_csrf_cookie, so any help will be greatly appreciated.

顺便说一句,使用 @csrf_exempt 按预期工作。

By the way, using @csrf_exempt works as expected.

在此先感谢。

推荐答案

ensure_csrf_cookie 可能只是1.4字母的功能,如果您无法将其导入 - 我导入它只是罚款与主干相同的语句。

ensure_csrf_cookie may only be a 1.4 alpha feature if you're having trouble importing it -- I can import it just fine with the same statement on trunk.

这里最简单的解决方案是通过csrf_token值Ajax调用本身。

The simplest solution here is to pass the csrf_token VALUE in the ajax call itself.

你说你使用jQuery。

You said you were using jQuery.

    $.ajax({
        url: "",
        type: 'POST',
        data: {
             csrfmiddlewaretoken: '{{ csrf_token }}' // just the token value
        },
        success: function(response) {
        }
    })

看来这种 ensure_csrf_cookie 强制视图设置,将需要使用的自动基于Cookie的CSRF保护机制,这里介绍jQuery的AJAX调用的CSRF的cookie:< A HREF =htt​​ps://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax相对=nofollow> https://docs.djangoproject.com/en/dev/ref/contrib / CSRF /#AJAX

It appears this ensure_csrf_cookie forces the view to set the csrf cookie that would be required for use in the automatic cookie based csrf protection mechanism for jquery ajax calls described here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

这篇关于Django中使用Ajax请求没有表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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