第一次海報,長時間讀者。我花了很長時間尋找答案,這讓我覺得它是我失蹤的根本。通過JSON將Django數據庫Queryset傳遞給Highcharts
我想拉數據庫表中的數據,並通過它顯示在Highcharts情節。在檢查源代碼時,我沒有從Django或客戶端收到任何錯誤。
使用:Django的1.7和Python 3.4
的views.py:
#unit/views.py
from django.http import JsonResponse
from django.shortcuts import render
from unit.analysis_funcs import ChartData
def chart_data_json(request):
data = {}
data['chart_data'] = ChartData.get_data()
return JsonResponse(data, safe = True)
def plot(request):
return render(request, 'unit/data_plot.html', {})
的GET_DATA()函數:
#unit/analysis_funcs.py
from unit.models import CheckValve
class ChartData(object):
def get_data():
data = {'serial_numbers': [], 'mass': []}
valves = CheckValve.objects.all()
for unit in valves:
data['serial_numbers'].append(unit.serial_number)
data['mass'].append(unit.mass)
return data
模板:
<!-- templates/unit/data_plot.html -->
{% extends "base.html" %}
{% block extrahead %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
{% endblock %}
{% block rootcontainer %}
<div id="container" style="width:100%; height:400px;"></div>
{% endblock %}
{% block overwrite %}
<!-- Overwrite the base.html jQuery load and put in head for Highcharts to work -->
{% endblock %}
{% block extrajs %}
<script>
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
series: [{}]
};
var ChartDataURL = "{% url 'chart_data_json' %}";
$.getJSON('ChartDataURL', function(data) {
options.xAxis.categories = data['chart_data']['serial_numbers'];
options.series[0].name = 'Serial Numbers';
options.series[0].data = data['chart_data']['mass'];
var chart = new Highcharts.Chart(options);
});
});
</script>
{% endblock %}
最後是網址:
from unit import views, graphs
urlpatterns = patterns('',
url(r'^chart_data_json/', views.chart_data_json, name = 'chart_data_json'),
url(r'^plot/', views.plot, name = 'plot'),
)
一切似乎都在運行,但Highchart情節並未呈現。我認爲它是關於如何將JSON數據從view.py移動到template.html的,但是經過這麼長時間的盯着它以後,我會發生一些對立的事情。
任何幫助將會很棒!
在控制檯中是否收到任何錯誤? –
@SebastianBochan檢索站點時沒有錯誤。獲得一個典型的200響應主要網址和URL調用數據 – peteza33