因此,我尝试使用 Django 中的 Highcharts 制作烛台图,但无法在网页上显示图表,而是显示所获取数据的 JSON 列表。
我正在使用 iexcloud 的 API 来获取历史数据
这是我的逻辑: 视图.py 文件:
def candlestick_chart_data(request):
api_key = 'my_api_key'
stock_data = get_historical_data(
"AAPL", start="2023-01-01", end="2023-05-05", output_format="pandas", token=api_key)
stock_data_array = [{
'x': date.isoformat(),
'open': row['open'],
'high': row['high'],
'low': row['low'],
'close': row['close']
} for date, row in stock_data.iterrows()]
return JsonResponse(stock_data_array, safe=False)
我的模板,即candlestick_chart.html
{% extends 'base.html' %}
{% block content %}
{% block home_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highcharts/9.2.1/css/highcharts.css"
integrity="sha512-bwK5pU3LlQlAocA38e/L90g86uJUZVvJEnpnT5ZyL0j3frzAKcJbhdTl0z0W4pVfTqBqftbX2y/3D2wLxbt6uQ=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/stock.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
{% endblock %}
<div id="container" style="height: 500px; width: 100%;"></div>
<script>
const dataURL = '{% url "candlestick-chart" %}';
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
const { chart } = e.target;
chart.showLoading('Loading data from server...');
fetch(`${dataURL}?start=${Math.round(e.min)}&end=${Math.round(e.max)}`)
.then(res => res.ok && res.json())
.then(data => {
console.log(data)
chart.series[0].setData(data);
chart.hideLoading();
}).catch(error => console.error(error.message));
}
fetch(dataURL)
.then(res => res.ok && res.json())
.then(data => {
data.forEach((d) => {
d.x = new Date(d.x);
});
// create the chart
Highcharts.stockChart('container', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'AAPL history by the minute from 1998 to 2011',
align: 'left'
},
subtitle: {
text: 'Displaying 1.7 million data points in Highcharts Stock by async server loading',
align: 'left'
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false, // it supports only days
selected: 4 // all
},
xAxis: {
events: {
afterSetExtremes: afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},
yAxis: {
floor: 0
},
series: [{
data: data,
dataGrouping: {
enabled: false
}
}]
});
}).catch(error => console.error(error.message));
</script>
{% endblock %}
以及我的 url 路径(如果需要):
path('candlestick-chart-data/', views.candlestick_chart_data, name='candlestick-chart'),
这是我在网页上得到的输出 本地主机网页图像
我尝试将 console.log 语句放入代码中,尝试在终端中打印数据,一切正常,但我无法理解为什么如果一切正常,图表不会出现在网页中
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我会赞同 @kikon 的建议 - 这将有助于 a) 查看正在生成的 localhost 页面的实际源代码,b) 查看控制台输出以查看是否抛出任何 JS 错误。如果没有看到这些,恐怕我无法在这里提供太多帮助。
但是,可能相关的一件事是,您当前正在 HTML
<body>中加载<script/>标记。这有点反模式,因为这意味着您的 Highcharts 构造函数 (
Highcharts.stockChart()) 可能会在相关 Highcharts 模块有机会加载之前执行,这将在控制台中抛出ReferenceError。更好的模式是在
<head/>块中包含<script/>标签,并使用defer属性,然后在 DOM 相关事件上触发 Highcharts 构造函数,例如DOMContentLoaded或类似的(确切的事件可能取决于您的具体用例/流程)。完成相同任务的另一种模式是使用重试的异步函数(捕获相关的
ReferenceError),直到加载脚本。当然,这些只是猜测 - 如果不查看 HTML 输出和控制台输出,很难准确确定这里发生了什么。
顺便说一句,如果您尝试将 Highcharts 集成到 Django 中,您可能还需要查看 Highcharts for Python 工具包刚刚作为 Highcharts 的付费插件发布(完全公开,我是 Highcharts for Python 工具包的创建者),它可以简化您的一些 Django 视图集成。 p>
同时,我希望这个答案可以帮助您诊断/解决问题,如果您分享更多详细信息,我很乐意通过更准确的诊断/建议来修改这个答案。