Chartjs-How to refresh chart in django without refreshing whole page

3👍

When django return rendered template to client, it won’t be able to make any changes afterwards. That’s why your chart doesn’t reflect any changes made in django.

If you need to update your chart with new data, easiest solution will be to use AJAX request.

  • User press Refresh button
  • Javascript send GET request to django API point
  • Django serve new values in JSON back to user
  • Javascript will update chart with new values

Make another endpoint, something like this:

from django.http import JsonResponse

def dashboard_ajax_chart_data(request):
    pass_tc=500
    failed_tc=99
    inprogress_tc=50
    data = {'data':[pass_tc, failed_tc, inprogress_tc]}
    return JsonResponse(data)

Make function in your javascript code, like this:

jQuery('.refresh-button').click(function(){
        jQuery.getJSON("/dashboard_ajax/", function(data, status)
        {
            chart.data.datasets[0].data = data.data;
            chart.update();
        }
        )
});

and make this function execute when you click on your refresh button.

I don’t have proper experience with chart.js, but use this guide to update your chart. https://www.chartjs.org/docs/latest/developers/updates.html

Leave a comment