Skip to content

Commit

Permalink
提交
Browse files Browse the repository at this point in the history
  • Loading branch information
qq516249940 committed Oct 22, 2022
1 parent f6e603a commit 7345d40
Show file tree
Hide file tree
Showing 31 changed files with 838 additions and 0 deletions.
Binary file added 2022-10-22-13-38-40.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
121 changes: 121 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
## 如何在 Django 中使用 pyecharts

Django 模板渲染模式

这里的django版本和官方介绍的不同。
本环境
django 4.1
pyecharts 1.9

[官网教程](https://pyecharts.org/#/zh-cn/web_django)

以下官网教程是不能在4.1 django 运行的,关注步骤即可,最终以本代码为准。



## Step 0: 新建一个 Django 项目
```bash
django-admin startproject pyecharts_django_demo
```
创建一个应用程序
```bash
python manage.py startapp demo
```
在 pyecharts_django_demo/settings.py 中注册应用程序

```bash
# pyecharts_django_demo/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo' # <---
]
```
编辑 demo/urls.py 文件
```bash
# demo/urls.py
from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
]

```
在 pyecharts_django_demo/urls.py 中新增 'demo.urls'

```bash
pyecharts_django_demo/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'demo/', include('demo.urls')) # <---
]
```
## Step 1: 拷贝 pyecharts 模板

先在 demo 文件夹下新建 templates 文件夹

```bash
chenjiandongx@DESKTOP-E83NUHA:/mnt/d/Python/pyecharts-django-demo/pyecharts_django_demo/demo$ ls
__init__.py __pycache__ admin.py apps.py migrations models.py templates tests.py urls.py views.py
```
将 pyecharts 模板,位于 pyecharts.render.templates 拷贝至刚新建的 templates 文件夹

```bash
chenjiandongx@DESKTOP-E83NUHA:/mnt/d/Python/pyecharts-django-demo/pyecharts_django_demo/demo/templates$ tree
.
├── jupyter_lab.html
├── jupyter_notebook.html
├── macro
├── nteract.html
├── simple_chart.html
├── simple_page.html
└── table.html
```

## Step 2: 渲染图表
将下列代码保存到 demo/views.py 中。

```bash
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig
from django.http import HttpResponse

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

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


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())
```
## Step 3: 运行项目
```bash
$ python manage.py runserver
```

## 运行有问题?
修改文件engine.py pyecharts包里面的文件
```
#第二行为如下
from collections.abc import Iterable
```

![](2022-10-22-13-38-40.png)
Empty file added db.sqlite3
Empty file.
Empty file added demo/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions demo/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions demo/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class DemoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'demo'
Empty file added demo/migrations/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions demo/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
13 changes: 13 additions & 0 deletions demo/templates/components.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{% import 'macro' as macro %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ chart.page_title }}</title>
</head>
<body>

{{ macro.gen_components_content(chart) }}

</body>
</html>
195 changes: 195 additions & 0 deletions demo/templates/macro
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
{%- macro render_chart_content(c) -%}
<div id="{{ c.chart_id }}" class="chart-container" style="width:{{ c.width }}; height:{{ c.height }};"></div>
<script>
var chart_{{ c.chart_id }} = echarts.init(
document.getElementById('{{ c.chart_id }}'), '{{ c.theme }}', {renderer: '{{ c.renderer }}'});
{% for js in c.js_functions.items %}
{{ js }}
{% endfor %}
var option_{{ c.chart_id }} = {{ c.json_contents }};
chart_{{ c.chart_id }}.setOption(option_{{ c.chart_id }});
{% if c._is_geo_chart %}
var bmap = chart_{{ c.chart_id }}.getModel().getComponent('bmap').getBMap();
{% if c.bmap_js_functions %}
{% for fn in c.bmap_js_functions.items %}
{{ fn }}
{% endfor %}
{% endif %}
{% endif %}
{% if c.width.endswith('%') %}
window.addEventListener('resize', function(){
chart_{{ c.chart_id }}.resize();
})
{% endif %}
</script>
{%- endmacro %}

{%- macro render_notebook_charts(charts, libraries) -%}
<script>
require([{{ libraries | join(', ') }}], function(echarts) {
{% for c in charts %}
{% if c._component_type not in ("table", "image") %}
var chart_{{ c.chart_id }} = echarts.init(
document.getElementById('{{ c.chart_id }}'), '{{ c.theme }}', {renderer: '{{ c.renderer }}'});
{% for js in c.js_functions.items %}
{{ js }}
{% endfor %}
var option_{{ c.chart_id }} = {{ c.json_contents }};
chart_{{ c.chart_id }}.setOption(option_{{ c.chart_id }});
{% if c._is_geo_chart %}
var bmap = chart_{{ c.chart_id }}.getModel().getComponent('bmap').getBMap();
bmap.addControl(new BMap.MapTypeControl());
{% endif %}
{% endif %}
{% endfor %}
});
</script>
{%- endmacro %}

{%- macro render_chart_dependencies(c) -%}
{% for dep in c.dependencies %}
<script type="text/javascript" src="{{ dep }}"></script>
{% endfor %}
{%- endmacro %}

{%- macro render_chart_css(c) -%}
{% for dep in c.css_libs %}
<link rel="stylesheet" href="{{ dep }}">
{% endfor %}
{%- endmacro %}

{%- macro display_tablinks(chart) -%}
<div class="tab">
{% for c in chart %}
<button class="tablinks" onclick="showChart(event, '{{ c.chart_id }}')">{{ c.tab_name }}</button>
{% endfor %}
</div>
{%- endmacro %}

{%- macro switch_tabs() -%}
<script>
(function() {
containers = document.getElementsByClassName("chart-container");
if(containers.length > 0) {
containers[0].style.display = "block";
}
})()

function showChart(evt, chartID) {
let containers = document.getElementsByClassName("chart-container");
for (let i = 0; i < containers.length; i++) {
containers[i].style.display = "none";
}

let tablinks = document.getElementsByClassName("tablinks");
for (let i = 0; i < tablinks.length; i++) {
tablinks[i].className = "tablinks";
}

document.getElementById(chartID).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
{%- endmacro %}

{%- macro generate_tab_css() %}
<style>
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}

.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 12px 16px;
transition: 0.3s;
}

.tab button:hover {
background-color: #ddd;
}

.tab button.active {
background-color: #ccc;
}

.chart-container {
display: none;
padding: 6px 12px;
border-top: none;
}
</style>
{%- endmacro %}

{%- macro gen_components_content(chart) %}
{% if chart._component_type == "table" %}
<style>
.fl-table {
margin: 20px;
border-radius: 5px;
font-size: 12px;
border: none;
border-collapse: collapse;
max-width: 100%;
white-space: nowrap;
word-break: keep-all;
}

.fl-table th {
text-align: left;
font-size: 20px;
}

.fl-table tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}

.fl-table tr:hover td {
background: #00d1b2;
color: #F8F8F8;
}

.fl-table td, .fl-table th {
border-style: none;
border-top: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-bottom: 3px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
padding: .5em .55em;
font-size: 15px;
}

.fl-table td {
border-style: none;
font-size: 15px;
vertical-align: center;
border-bottom: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
height: 30px;
}

.fl-table tr:nth-child(even) {
background: #F8F8F8;
}
</style>
<div id="{{ chart.chart_id }}" class="chart-container" style="">
<p class="title" {{ chart.title_opts.title_style }}> {{ chart.title_opts.title }}</p>
<p class="subtitle" {{ chart.title_opts.subtitle_style }}> {{ chart.title_opts.subtitle }}</p>
{{ chart.html_content }}
</div>
{% elif chart._component_type == "image" %}
<div id="{{ chart.chart_id }}" class="chart-container" style="">
<p class="title" {{ chart.title_opts.title_style }}> {{ chart.title_opts.title }}</p>
<p class="subtitle" {{ chart.title_opts.subtitle_style }}> {{ chart.title_opts.subtitle }}</p>
<img {{ chart.html_content }}/>
</div>
{% endif %}
{%- endmacro %}
5 changes: 5 additions & 0 deletions demo/templates/nb_components.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% import 'macro' as macro %}

{% for chart in charts %}
{{ macro.gen_components_content(chart) }}
{% endfor %}
45 changes: 45 additions & 0 deletions demo/templates/nb_jupyter_globe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<script>
require.config({
paths: {
{{ config_items | join(', ') }}
}
});
</script>

{% for chart in charts %}
<div id="{{ chart.chart_id }}" style="width:{{ chart.width }}; height:{{ chart.height }};"></div>
{% endfor %}


<script>
require([{{ libraries | join(', ') }}], function(echarts) {
{% for c in charts %}
var canvas_{{ c.chart_id }} = document.createElement('canvas');
var mapChart_{{ c.chart_id }} = echarts.init(
canvas_{{ c.chart_id }}, '{{ c.theme }}', {width: 4096, height: 2048, renderer: '{{ c.renderer }}'});
var mapOption_{{ c.chart_id }} = {{ c.json_contents }};
mapChart_{{ c.chart_id }}.setOption(mapOption_{{ c.chart_id }});
var chart_{{ c.chart_id }} = echarts.init(
document.getElementById('{{ c.chart_id }}'), '{{ c.theme }}', {renderer: '{{ c.renderer }}'});
{% for js in c.js_functions.items %}
{{ js }}
{% endfor %}
var option_{{ c.chart_id }} = {
"globe": {
"show": true,
"baseTexture": mapChart_{{ c.chart_id }},
shading: 'lambert',
light: {
ambient: {
intensity: 0.6
},
main: {
intensity: 0.2
}
}

}};
chart_{{ c.chart_id }}.setOption(option_{{ c.chart_id }});
{% endfor %}
});
</script>
Loading

0 comments on commit 7345d40

Please sign in to comment.