How to refresh chart in django without refreshing whole page

I am new to Django , i Have used chart.js to populate a chart in HTML . I want to refresh the chart without loading the HTML itself.

HTML Chart look like below

CHart present in HTML

View corresponding to the URL for above HTML is below

**Views.py**

   from __future__ import unicode_literals

from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
def dashboard(request):
    if request.is_ajax():
        print "this is ajax request inside dashboard function"
        pass_tc=29
        failed_tc=25
        inprogress_tc=25
        data = {'data':[pass_tc, failed_tc, inprogress_tc]}
        request.GET.get('data')
        print JsonResponse(data)
        return JsonResponse(data)

    context = {'data':[500,100,50]}
    template='dashboard.html'

    return render(request,template,context)



]

In HTML , i have used updateChart() functionality of Chart.js

<button class='btn btn-success' onclick="updateChart()">Refresh</button>

         <script>
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'bar',

        // The data for our dataset
        data: {
        labels: ['Pass', 'Fail', 'Inprogress'],
        datasets: [{
            label: 'Results',
            //backgroundColor: 'rgb(255, 99, 132)',
            //borderColor: 'rgb(255, 99, 132)',
            backgroundColor:[
            'green','Brown','orange'],
            data: [10, 10,15]
        }]
        },

    // Configuration options go here
        options: {},

        });
        function updateChart(){

   $.get("/dashboard/",{data:response.JsonResponse(data)}, function(data, status)
    {
        //console.log(data)

        chart.data.datasets[0].data={{data}};
        chart.update();
    }


        )


        };

On the server side i can see below response

this is ajax request inside dashboard function
Content-Type: application/json

{"data": [29, 25, 25]}
[15/Apr/2019 18:52:12] "GET /dashboard/ HTTP/1.1" 200 22

So the Ajax request is fetching the data . However my chart is not getting populated with this data.

it uses the non Ajax data defined in View.py, also shown in graph i.e.

{'data':[500,100,50]}

What wrong i am doing in my Ajax request.

1 answer

  • answered 2019-04-15 06:45 Gasanov

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