jQuery:设置用于Django的CSRF令牌不工作 [英] jQuery: setting up CSRF token for Django not working

查看:127
本文介绍了jQuery:设置用于Django的CSRF令牌不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 jQuery 函数看起来像

$(function() {
    // activate "New" buttons if input is not empty
    $('form input[type="text"]').live('keyup', function() {
        var val = $.trim(this.value);
        $(this).next("button").prop('disabled', val.length === 0);
    });

    $("body").on("submit","form",function(e){
        // do not submit the form
        e.preventDefault();

        // handle everything yourself
        var $form = $(this);
        var title = $form.closest('.video-detail').find('.title').text();
        var entryTitle = $form.find('.input-small').val();
        console.debug(title);
        console.debug(entryTitle);  

        $.ajaxSetup({ 
             beforeSend: function(xhr, settings) {
                 function getCookie(name) {
                     var cookieValue = null;
                     if (document.cookie && document.cookie != '') {
                         var cookies = document.cookie.split(';');
                         for (var i = 0; i < cookies.length; i++) {
                             var cookie = jQuery.trim(cookies[i]);
                             // Does this cookie string begin with the name we want?
                         if (cookie.substring(0, name.length + 1) == (name + '=')) {
                             cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                             break;
                         }
                     }
                 }
                 return cookieValue;
                 }
                 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                     // Only send the token to relative URLs i.e. locally.
                     xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                 }
             } 
        }); 

        // send the data to the server using .ajax() or .post()
        $.ajax({
            type: 'POST',
            url: 'addVideo',
            data: {
                video_title: title,
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
        }).done(function(){
            alert('done');
        });
    });
});

这是基于答案 Django CSRF检查失败,使用Ajax POST请求

我的 html 看起来像

<form class="new-playlist form-inline" onclick="event.stopPropagation()">{% csrf_token %}
    <input type="text" class="input-small">
    <button class="btn btn-danger create-playlist-button" type="submit" disabled="disabled">New</button>
</form>

当我在Firefox中调试代码时,我看到帖子值为

When I debug the code in Firefox, I see post values as

csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?

如何填充 {{csrf_token}} 值?

谢谢

推荐答案

在我的情况下有一个模板,我不想要一个< form>< / form> 元素。但是我仍然想使用jQuery来制作AJAX POST请求。

In my case I have a template in which I don't want to have a <form></form> element. But I still want to make AJAX POST requests using jQuery.

由于CSRF cookie为null,因此我有403个错误,即使我遵循django文档( https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/ )。解决方案在同一页面,提到 ensure_csrf_cookie 装饰器。

I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie decorator.

我添加了CSRF cookie这在我的 views.py 的顶部:

My CSRF cookie did get set when I added this at the top of my views.py:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

另请注意,在这种情况下您不需要标记/模板中的DOM元素: {%csrf_token%}

Also, please note that in this case you do not need the DOM element in your markup / template: {% csrf_token %}

这篇关于jQuery:设置用于Django的CSRF令牌不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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