[Django]-Updating a Django list view with ajax

4👍

Use setInterval to refresh the concerned page of HTML every specific second.

var refreshStream = function(){
    $.ajax({
        url: '/url_to_view/',
        method: 'GET',
        data: {},
        success: function(data){
            $('#stream-list').replaceWith($('#stream-list',data));
        },
        error: function(error){
            console.log(error);
            console.log("error");
        }
    });
}

var total_seconds = 5; // refresh every 5 seconds

setInterval(function(){
    refreshStream();
},total_second * 1000);

Keep your view the way it was:

def streams_list(request):
    streams_ranked = StreamPost.objects.annotate(q_count=Count('upvotes')) \
                                    .order_by('-q_count')
    context = {
        'streams_ranked' : streams_ranked,
        'form': StreamPostForm()
    }

    return render(request, 'streams/leaderboard_list.html', context)

Leave a comment