简体   繁体   中英

getting list from django views to googlecharts in templates

I am trying to get sensor data from postgresql database to googlecharts in django, but I am unable to get the charts though data shows when I write {{ sensor_data }} in template. Can anyone tell what I am doing wrong here, this is the template:

<html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {packages: ['corechart']});
    google.charts.setOnLoadCallback(drawChart);


    function drawChart() {
      // Define the chart to be drawn.
      var data = new google.visualization.DataTable();
      data.addColumn('datetime','Date/Time');
      data.addColumn('number','Temperature');
      {% for data in sensor_data %}
    data.addRow([new Date("{{ data.data_date }}"), {{ data.amb_temp }}]);
      {% endfor %}  

      var chart = new google.visualization.LineChart(document.getElementById('myPieChart'));
      chart.draw(data, null);
    }
  </script>
</head>

<body>

<div id="myPieChart" style="width: 900px; height: 500px;"></div>
    <a href="/polls/{{node.id }}/"></a>

</body>
</html>

this is the view:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from .models import *
import json
from django.core.serializers.json import DjangoJSONEncoder

def date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        return obj

def history(request,node):
    if request.method == 'GET':
        try:           
            crop=bitter_gourd_node_c.objects.filter(node_id=node).values_list('data_date','amb_temp')   
        sensor_data = []
            if crop:
                for i in range(0, len(crop)):
                    sensor_data.append([crop[i]])
            json_list = json.dumps(sensor_data, cls=DjangoJSONEncoder)
            return render(request,'history.html', {"sensor_data": reversed(json_list)})
        except Nodes.DoesNotExist:
            return HttpResponseForbidden

    return HttpResponseForbidden

and this is the model:

class bitter_gourd_node_c(models.Model):
    node_id=models.ForeignKey(Nodes)
    record_no= models.AutoField(blank=True,primary_key=True)    
    data_date=models.DateTimeField()
    humidity=models.DecimalField(max_digits=14,decimal_places=10)
    amb_temp=models.DecimalField(max_digits=14,decimal_places=10)
    deep_under_temp=models.DecimalField(max_digits=14,decimal_places=10)
    shallow_under_temp=models.DecimalField(max_digits=14,decimal_places=10)
    deep_soil_moisture=models.DecimalField(max_digits=14,decimal_places=10)
    shallow_soil_moisture=models.DecimalField(max_digits=14,decimal_places=10)
    ldr=models.DecimalField(max_digits=14,decimal_places=10)

Why are you converting sensor_data to JSON?

json_list = json.dumps(sensor_data, cls=DjangoJSONEncoder)
return render(request,'history.html', {"sensor_data": reversed(json_list)})

It is not necessary to convert it to json.

return render(request,'history.html', {"sensor_data": sensor_data})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM