我想從postgresql數據庫中獲取傳感器數據到django中的googlecharts,但是我無法獲取圖表,但是我在數據顯示模式下編寫{{sensor_data}}時顯示圖表。誰能告訴我在做什麼錯在這裏,這是模板:從django視圖獲取列表到模板googlecharts
<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>
本所認爲:
# -*- 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
,這是模型:
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)
我並不完全明白你的問題。但我建議你嘗試調試,如果你在JS中獲得期望的值,例如在你的for循環中添加一行「console.log()」並穹頂日期和值,以確保它們如你所期望的那樣正確 –
錯誤:給出的行大小不同於2(表中的列數)。不斷得到這個錯誤,即使我在終端檢查len(sensor_data [0])函數顯示2作爲輸出。 –
好吧,這意味着你的循環中有一個值有錯誤或未定義的值。請嘗試console.log(新日期(「{{data.data_date}}」),{{data.amb_temp}})。在addRow之前,看看哪一行是錯誤的 –