首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django :从jQuery提交表单时未设置CSRF cookie

问Django :从jQuery提交表单时未设置CSRF cookie
EN

Stack Overflow用户
提问于 2012-08-04 22:18:17
回答 2查看 4.8K关注 0票数 0

我的jQuery函数看起来像

代码语言:javascript
复制
$("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);

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

我的urls.py看起来就像

代码语言:javascript
复制
urlpatterns = patterns('',
    url(r'^$', home),
    url(r'^done$', done, name='done'),
    url(r'', include('social_auth.urls')),
    url(r'^addVideo$', addVideo)
)

我的views.py看起来就像

代码语言:javascript
复制
@login_required()
@transaction.commit_on_success
def addVideo(request):
    logging.info('add Video request - ' + str(request))
    pass

当我运行我的web应用程序时,我使用firebug调试控制台,我看到了错误。

代码语言:javascript
复制
my.js (line 96)
POST http://myaap.in/addVideo

403 FORBIDDEN    43ms

当我进一步钻研的时候,我看到了

代码语言:javascript
复制
<div id="summary">
  <h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>

</div>

<div id="info">
  <h2>Help</h2>

    <p>Reason given for failure:</p>
    <pre>
    CSRF cookie not set.
    </pre>


  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  <a
  href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's
  CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
  ensure:</p>

  <ul>
    <li>Your browser is accepting cookies.</li>

    <li>The view function uses <a
    href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext'><code>RequestContext</code></a>
    for the template, instead of <code>Context</code>.</li>

    <li>In the template, there is a <code>{% csrf_token
    %}</code> template tag inside each POST form that
    targets an internal URL.</li>

    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code>
    template tag, as well as those that accept the POST data.</li>

  </ul>
  • 我是Django和web development的新手,我不太明白这意味着什么
  • 请帮助我理解我需要学什么来解决这个问题。

更新

我的表格看起来

代码语言:javascript
复制
<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>

更新1在添加来自Django CSRF检查在Ajax POST请求中失败的代码后,我将post数据视为

代码语言:javascript
复制
csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?
Source
video_title=The+Who+-+Who+Are+You%3F&csrfmiddlewaretoken=%7B%7B+csrf_token+%7D%7D

我的jQuery现在看起来

代码语言:javascript
复制
// setting up ajaxSetup
$(function(){
    $.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'));
             }
         } 
    });
});
// creating new playlist
$(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);      

        // 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');
        });
    });
});

谢谢

EN

回答 2

Stack Overflow用户

发布于 2012-08-04 22:36:05

Django试图保护您免受CSRF 坚持要你提供一个CSRF令牌的攻击。通常--如果您是通过普通POST提交表单--启用它非常容易,您只需执行以下操作:

代码语言:javascript
复制
<form action="." method="post">{% csrf_token %}

但是,由于您使用的是AJAX,所以它要复杂一些。查看一下他们的建议的django文档,或者看到前面的问题处理这个问题。

本质上,在使用AJAX时,您需要手动提供和提交令牌,但是最好的解决方案似乎取决于django的版本。

票数 0
EN

Stack Overflow用户

发布于 2012-08-04 22:44:19

尝试使用传递结果$form.serialize()作为$.ajax()的数据。只要表单模板中有{% csrf_token %},它就会选择表单中的所有值(包括令牌)并发送AJAX调用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11812396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档