Django2.* 模板语言结合使用百度ECharts,支持bootstrap4
学习Django过程中遇到一个使用ECharts,记录下遇到的坑
ECharts官方示例
使用如图样板官方示例,展示4个出版社,每个月新书量,
Model
以书出版社简单关系为例
view
根据ECharts需要两个数据source:[]、encode:{},首先根据当前时间,生成月份列表,这里使用了count()取每个月出版书的数量,最后返回数据
from django.shortcuts import render
from models import Books, Publisher
import datetime
def list(request):
if request.method == "GET":
today = datetime.datetime.now()
one_year_data = Publisher.objects.filter(pub_time = today.year) # 取出一年的数据
source_list = []
yue_list = ['month'] #定义月份数据
for m in range(1,today.month+1):
m = str(m)+'月'
yue_list.append(m)# 取 12个月
source_list.append(yue_list)
for item in Publisher.objects.all():
temp_list = [item.title]
for m in range(1,today.month+1):
count = one_year_data.filter(pub_time__month = m,title = item.id).count()
temp_list.append(count)# 取出一个月有多少本书
source_list.append(temp_list)
now_month = str(today.month)+'月'
return render(request,"list.html",
{
"source_list":source_list,
"now_month":now_month
}
)
list.html
div:
<div id ="main" style="width:100%;height:400px;"></div>
js:
var myChart = echarts.init(document.getElementById('main'));
var source_list = {{source_list |safe}};
setTimeout(function () {
option = {
legend: {},
tooltip: {
trigger: 'axis',
showContent: false
},
dataset: {
source: source_list
},
xAxis: {type: 'category'},
yAxis: {gridIndex: 0},
grid: {top: '55%'},
series: [
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{
type: 'pie',
id: 'pie',
radius: '30%',
center: ['50%', '25%'],
label: {
formatter: '{b}: {@ {{now_month |safe}}} ({d}%)'
},
encode: {
itemName: 'product',
value: {{now_month |safe}},
tooltip: {{now_month |safe}}
}
}
]
};
myChart.on('updateAxisPointer', function (event) {
var xAxisInfo = event.axesInfo[0];
if (xAxisInfo) {
var dimension = xAxisInfo.value + 1;
myChart.setOption({
series: {
id: 'pie',
label: {
formatter: '{b}: {@[' + dimension + ']} ({d}%)'
},
encode: {
value: dimension,
tooltip: dimension
}
}
});
}
});
myChart.setOption(option);
});
兼容bootstrap4
首先需要将div height设置100%,在 myChart.setOption(option);后添加如下代码
window.addEventListener("resize",function(){
myChart.resize();
})