3

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 ?

1
  • 5
    You are note fetching new data from the database, you will need to make an ajax call inside the ChartUpdate function. You may need to implement a new API endpoint. Commented May 4, 2019 at 15:28

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Good question, great answer. And in fact, to achieve live updates, you need setInterval and $.ajax()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.