Django使用Echarts、Pyecharts

https://mp.weixin.qq.com/s/ZnBzGL3wlWIVONrUV7_EPQ

  1. Echarts
# 1.
from django.http import JsonResponse
from django.shortcuts import render


def index_view(request):
    if request.method == "POST":

        # 柱状图的数据
        datas = [5, 20, 36, 10, 10, 20]

        # 返回数据
        return JsonResponse({'bar_datas': datas})
    else:
        return render(request, 'index.html', )


# 2. 
{#导入js和echarts依赖#}
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.0.2/echarts.common.js"></script>

# 3. 
# 重写 window.onload 函数,发送一个 Ajax 请求给后端,利用 Echarts 将返回结果展示到图表中去
<script>
    // 柱状图
    function show_bar(data) {

        //控件
        var bar_widget = echarts.init(document.getElementById('bar_div'));

        //设置option
        option = {
            title: {
                text: '简单的柱状图'
            },
            tooltip: {},
            legend: {
                data: ['销量']
            },
            xAxis: {
                type: 'category',
                data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: data,
                type: 'bar'
            }]
        };

        bar_widget.setOption(option)
    }

    //显示即加载调用
    window.onload = function () {
        //发送post请求,地址为index(Jquery)
        $.ajax({
            url: "/",
            type: "POST",
            data: {},
            success: function (data) {
                // 柱状图
                show_bar(data['bar_datas']);

                //后端返回的结果
                console.log(data)
            }
        })
    }
</script>

# 4. 
#最后,编写路由 URL,运行项目

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('',include('index.urls')),
    path('admin/', admin.site.urls),
]

  1. Pyecharts
# 1. 
pip3 install pyecharts

# 2. 
#拷贝 pyecharts 的模板文件到项目下
/python3.7/site-packages/pyecharts/render/templates/

# 3. 
# 编写视图函数,渲染图表
# 在视图文件中,使用 pyecharts 库内置的类 Bar 创建一个柱状图

# Create your views here.
from django.http import HttpResponse
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig

CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./index/templates"))

from pyecharts import options as opts
from pyecharts.charts import Bar


# http://127.0.0.1:8000/demo/
def index(request):
    c = (
        Bar()
            .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
            .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
            .add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
    )
    return HttpResponse(c.render_embed())

原文地址:https://www.cnblogs.com/amize/p/14621406.html