2017-02-06 7 views
1

私はこのようになりますコメントのクエリセットがあります。そして、私のテンプレートがAJAXを使用してクエリーセットを変更することはできますか?

{% for comment in comment_list %} 
    {{ comment }} 

... 

ある

comment_list = Comment.objects.filter().order_by('-score__upvotes') 
new_comments_list = Comment.objects.filter().order_by('-timestamp') 

は、AJAX(ノーページの更新)を使用して{% for comment in new_comments_list %}{% for comment in comment_list %}を変更する方法はありますか?

おそらくcomment_listの値をComment.objects.filter().order_by('-timestamp')に変更しますか?

答えて

1

AJAXリクエストは、開発者(あなた)がそう言ったときに発生します。たとえば、AJAXリクエストを行うために特定のボタンを「クリックする」ことでイベントリスナーを設定した場合、AJAXリクエストが行われます。

で特定のボタンのクリックイベントを「リッスンする」イベントリスナーがあるとします。

{# Place this as a separate html file, say "ajax_comments.html" #} 
<div id="my-placeholder"> 
    {% for comment in comments %} 
     {{ comment }} 
    {% endfor %} 

    <button id="my-button">Update comments</button> 
</div> 
{# END OF PLACE THIS #} 

{# ############################################################### #} 

{# Begin of your main HTML template, say "my_template.html" #} 

.... 

{% include 'path/to/ajax_comments.html' %} 

.... 

// make an Ajax call (GET request) to the same url, using jQuery. 
$(document).ready(function() { 
    $('#my-button').on('click', function() { 
     $.ajax({ 
      'method': 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too! 
      'url': '.', // submit to the same url 
      'data': {}, // pass here any data to the server. You can omit it. 
      success: function(dataReturned) { 
       // This function will run when server returns data 
       $('#my-placeholder').replaceWith(dataReturned); 
      } 
     }); 
    }); 
}); 

{# END OF "my_template.html" #} 

HTML、JSで終了します。今すぐあなたのviews.pyに。

def my_view(request): 
    if request.is_ajax(): 
     # If you have passed any data through the 'data' property 
     #you can get it here, according to the method used. 
     my_data = request.GET.get('data-name') 
     comments = Comment.objects.filter().order_by('-timestamp') 
     # Note that we are passing the 'ajax_comments.html' template. 
     return render(request, 'ajax_comments.html', {'comments': comments}) 

    comments = Comment.objects.filter().order_by('-score__upvotes') 
    return render(request, 'my_template.html', {'comments': comments}) 
  1. ボタンは、AJAXリクエストがあなたの意見の中に、サーバー
  2. に作られ、あなたが要求のこの種を扱う、あなたが新しいとHTML部分を返す
  3. テンプレートに押されクエリーセット
  4. このリターンはテンプレートに直接レンダリングされませんが、これを待っている関数$.ajax()に行きます。
  5. 一度受け取った、それは(新しいものにdivのデータを交換する)私たちがやって書いたものを行い

希望これはあなたを助けます!

+0

返信いただきありがとうございます。私はあなたに非常に似たようなコードを使ってクエリーセットを変更することができましたが、何らかの理由で、新たにロードされた子テンプレートでJavaScriptが動作していません。理由は何ですか?私はここに質問をしました:http://stackoverflow.com/questions/42126427/js-stops-working-on-child-template-when-i-perform-an-ajax-call-to-change-the- que?noredirect = 1#comment71422842_42126427 – Zorgan

関連する問題