我正在尝试通过以下解决方案在Highchart的帮助下显示图表:
Passing Django Database Queryset to Highcharts via JSON
但是我无法显示数据:
还是新手,感谢你的帮助,伙计们!
views.py
class ChartData(object):
def check_valve_data():
data = {'member_no': []}
people = Member.objects.all()
for unit in people:
data['member_no'].append(unit.member_no)
return data
def chartViewHigh(request, chartID='chart_ID', chart_type='column', chart_height=500):
data = ChartData.check_valve_data()
chart = {"renderTo": chartID, "type": chart_type, "height": chart_height, }
title = {"text": 'Check Member Data'}
xAxis = {"title": {"text": 'Member'}, "categories": data['member_no']}
yAxis = {"title": {"text": 'Data'}}
return render(request, 'chart/chartViewHigh.html', {'chartID': chartID, 'chart': chart,
'title': title, 'xAxis': xAxis, 'yAxis': yAxis})
chartViewHigh.html
{% extends 'base.html' %}
{% load staticfiles i18n %}
{% block head %}
<link href="{% static 'css/chart.css' %}" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
{% endblock head %}
{% block main %}
<h1 align="center">Analysis</h1>
{% block content %}
<div id={{ chartID|safe }} class="chart" style="height:100px; width:100%"></div>
{% endblock %}
{% block extrajs %}
<script>
var chart_id = {{ chartID|safe }};
var chart = {{ chart|safe }};
var title = {{ title|safe }};
var xAxis = {{ xAxis|safe }};
var yAxis = {{ yAxis|safe }};
</script>
<script>
$(document).ready(function() {
$(chart_id).highcharts({
chart: chart,
title: title,
xAxis: xAxis,
yAxis: yAxis,
});
});
</script>
{% endblock %}
{% endblock main %}
urls.py
urlpatterns = patterns[
url(r'^chartViewHigh/$', views.chartViewHigh, name='chartViewHigh'),
]
答案 0 :(得分:1)
一些问题:
您需要在图表ID模板变量周围使用引号来使其成为HTML属性:
<div id="{{ chartID|safe }}" ...
您没有传入有效的JQuery选择器:要选择上面的div,您应该使用$("#chart_ID")
(请参阅JQuery selectors),所以使用Django模板变量,例如:
$("#{{ chartID|safe }}")
此外,数据似乎需要series
键才能渲染(我没有使用过高图,但请参阅此处 - 添加时会显示图表):
https://www.highcharts.com/docs/getting-started/your-first-chart
ChartData
类也不属于您的views.py文件 - 只有HTTP请求/响应属于那里。如果您还没有了解“Django方式”来做事,我建议您通过Django官方教程。例如,您的ChartData
方法会生成一个member_nos列表,但您可以使用一行代码执行此操作:)
Member.objects.values_list('member_no', flat=True)