Eddie.W
Eddie.W

Reputation: 143

How to create dynamic charts with Django and Chart.js?

I'm creating a web page, and want to include a chart that shows the evolution of temperature during time.

Temperature data are saved in a database every seconds. Django retrieve this data and pass it to the template.

Django :

def Dashboard(request):

    temp = Info.objects.using('wings').filter(localisation ='Wing_1').order_by('-time')

    time1 = []
    temperature = []

    for dataset in temp :
        time1.append(dataset.time.strftime("%Hh%M"))
        temperature.append(dataset.temp_wing)

    time1 = time1[:60]
    temperature = temperature[:60]
    time1.reverse()
    temperature.reverse()

    context = {
                'time1': time1,
                'temperature': temperature,
    }
    return render(request, 'Dashboard/dashboard.html',context)

Template :

<!DOCTYPE html>
{% load static %}

<canvas id="myChart" width="400" height="200"></canvas>

<script src="{% static 'Dashboard/js/Chart.min.js' %}"></script>

<script>
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: {{time1|safe}},
        datasets: [
        {label: 'Wing 1 temperature', data : {{temperature|safe}}, backgroundColor:['rgba(54, 162, 235, 0.2)'], borderColor: ['rgba(54, 162, 235, 1)'], borderWidth: 1}
        ]},
    options: {
        scales: { yAxes: [{ ticks: { beginAtZero: false }}]}
        }
    });

ChartUpdate(function(){
  myChart.data.datasets[0].data = {{temperature|safe}};
  myChart.data.labels = {{time1|safe}};
  myChart.update();
}, 5000);

</script>

The chart is properly rendered with the value of the database. But I had expected that the ChartUpdate function in the template will automatically update the graph with the value freshly saved in the database, but it doesn't seem to work...

Is there a way to automatically update the value of the chart with the new value of a database without reloading the page ?

Upvotes: 3

Views: 6360

Answers (1)

Eddie.W
Eddie.W

Reputation: 143

Thanks to drec4s comment, I was able to solve my problem !

Here the view file :

def AutoUpdate(request):

    temp = Info.objects.using('wings').filter(localisation ='Wing_1').order_by('-time')

    time1 = []
    temperature = []

    for dataset in temp :
        time1.append(dataset.time.strftime("%Hh%M"))
        temperature.append(dataset.temp_wing)

    time1 = time1[:60]
    temperature = temperature[:60]
    time1.reverse()
    temperature.reverse()

    context = {
                'time1': time1,
                'temperature': temperature,
    }
    return JsonResponse(context)

And the script part in the template :

setInterval(function(){
    $.ajax({
        url:'/Dashboard/AutoUpdate',
        success: function(test){
            myChart.data.datasets[0].data = test.temperature;
            myChart.data.labels = test.time1;
            myChart.update();
        }
    });
}, 5000);

Upvotes: 6

Related Questions