赞
踩
官网教程参考:https://pyecharts.org/#/zh-cn/web_django?id=django-%e6%a8%a1%e6%9d%bf%e6%b8%b2%e6%9f%93
这篇博客与官网一样使用Ajax
,不使用ajax,直接填充一个div的请参考:django填充pyechart的图到前端模版中(不使用Ajax,而是直接贴一个div)
官网教程版本不太对,这里重写一下,顺便解决官网一些规范性的问题
首先需要明确,pyechart是通过python来生成HTML(echart)的工具,在django中,则是通过Ajax填充
在流程中前三部分都是为了项目准备:
安装必要的依赖:
pip install django
pip install pyecharts
pip install djangorestframework
版本:
python 3.7.13
Django 3.2.13
djangorestframework 3.13.1
pyecharts 1.9.1
然后创建django项目
django-admin startproject pyecharts_django_demo
cd pyecharts_django_demo/
python manage.py startapp demo
pyecharts_django_demo/settings.py
文件中,修改INSTALLED_APPS
的配置,在文件中添加两个配置项:rest_framework
与刚才创建的demo
,最后的结果如下:INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"rest_framework",
"demo",
]
INSTALLED_APPS
的上面添加下面的代码,方便后续操作:import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
TEMPLATES
的DIRS
,之前"DIRS"那里是个空列表,咱们要填一下,这是固定写法:TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, 'templates')], # 说明你的HTML文件放在哪里,后面会添加这个文件夹,这里先配置上
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
在demo/
文件夹下新建一个urls.py
文件,然后在新建的文件中写入:
from django.urls import path
from . import views
urlpatterns = [
path(r'^index/$', views.IndexView.as_view(), name='demo'),
path(r'where_is_my_pic/', views.PicView.as_view(), name='my_pic'),
]
这里咱们先把路径都配好,调通了之后再串逻辑
定位到项目根目录的url.py
文件(在pyecharts_django_demo/urls.py
即为项目根目录的urls文件):
from django.urls import include
demo
的路由最后修改完后的效果如下:
"""pyecharts_django_demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(r'demo/', include('demo.urls')) ]
在项目根目录下,与manage.py
同一个目录下,创建一个templates
文件夹(名字不要错,固定写法),之后的文件结构是:
templates
文件夹下创建一个index.html
文件:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Awesome-pyecharts</title> <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script> </head> <body> <div id="my_piccccc" style="width:1000px; height:600px;"></div> <script> var chart = echarts.init(document.getElementById('my_piccccc'), 'white', {renderer: 'canvas'}); $( function () { fetchData(chart); } ); function fetchData() { $.ajax({ type: "GET", url: "http://127.0.0.1:8000/demo/where_is_my_pic", // 这个是请求后端的url dataType: 'json', success: function (result) { chart.setOption(result.data); } }); } </script> </body> </html>
demo/view.py
中写入:import json from random import randrange from django.http import HttpResponse from rest_framework.views import APIView from pyecharts.charts import Bar from pyecharts import options as opts from django.shortcuts import render # 下面的代码是AJAX的写法 def response_as_json(data): json_str = json.dumps(data) response = HttpResponse( json_str, content_type="application/json", ) response["Access-Control-Allow-Origin"] = "*" return response def json_response(data, code=200): data = { "code": code, "msg": "success", "data": data, } return response_as_json(data) def json_error(error_string="error", code=500, **kwargs): data = { "code": code, "msg": error_string, "data": {} } data.update(kwargs) return response_as_json(data) JsonResponse = json_response JsonError = json_error # 这是返回图片的写法 class PicView(APIView): def get(self, request, *args, **kwargs): my_pic = ( Bar() .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]) .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)]) .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)]) .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")) .dump_options_with_quotes() ) return JsonResponse(json.loads(my_pic)) # 这是显示页面的写法 class IndexView(APIView): def get(self, request, *args, **kwargs): return render(request, 'index.html', )
访问:http://127.0.0.1:8000/demo/
然后我们就可以照猫画虎的魔改代码了,只需要:
my_piccccc
,这个名字自己定。其中一个出现在div中,一个出现在js的document.getElementById('my_piccccc')
中,这两个要对应上fetchData
中有一行url:xxxxx
:function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/where_is_my_pic", // 这个是请求后端的url
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
这个与第三步中的配置pyechart的图片路由 一一对应
3. 在view.py
中函数def get(self,request)
写法固定,函数名不要改,内容随便,可以修改成任意图片,然后注意还要与url.py
的路由对应上
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。