0

私のjQuery関数は次のようになります

$("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見えます

urlpatterns = patterns('',
    url(r'^$', home),
    url(r'^done$', done, name='done'),
    url(r'', include('social_auth.urls')),
    url(r'^addVideo$', addVideo)
)

views.pyのように見えます

@login_required()
@transaction.commit_on_success
def addVideo(request):
    logging.info('add Video request - ' + str(request))
    pass

Webアプリを実行すると、firebugを使用してコンソールをデバッグします。エラーが表示されます。

my.js (line 96)
POST http://myaap.in/addVideo

403 FORBIDDEN    43ms

それに応じてさらにドリルすると、

<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>
  • 私は初めてでDjangoweb development一緒にいて、それが何を意味するのか本当に理解していません
  • これを修正するために私が学ぶ必要があることを理解するのを手伝ってください

アップデート

私のフォームは次のようになります

<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>

UPDATE 1 Django CSRFチェック からコードを追加した後、AjaxPOSTリクエストで失敗しました 投稿データは次のように表示されます

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は今のように見えます

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

ありがとうございました

4

2 に答える 2

0

Djangoは、CSRFトークンを提供するように要求することで、 CSRFからユーザーを保護しようとしています。通常、通常のPOSTを介してフォームを送信する場合は、有効にするのは非常に簡単です。次の手順を実行するだけです。

<form action="." method="post">{% csrf_token %}

ただし、AJAXを使用しているため、少し複雑になります。推奨事項についてはdjangoのドキュメントを参照するか、問題を扱っている前の質問を参照してください。

基本的に、AJAXを使用する場合はトークンを手動で提供して送信する必要がありますが、最善の解決策はdjangoのバージョンによって異なります。

于 2012-08-04T22:36:05.733 に答える
0

$form.serialize()結果を のデータとして渡してみてください$.ajax(){% csrf_token %}フォーム テンプレートのどこかに存在している限り、フォーム内のすべての値 (トークンを含む) が選択され、AJAX 呼び出しが送信されます。

于 2012-08-04T22:44:19.243 に答える