How to use pyecharts in Django

Create a new directory for the project, name it Django \ _ pyecharts \ _ demo, change to this directory in the terminal, and create a virtual environment.

python -m venv django_pyecharts 

Activate the virtual environment

django_pyecharts\Scripts\activate 

To stop using the virtual environment, execute the command

deactivate 

Once the virtual environment is created and activated, Django can be installed

(django_pyecharts)learning_log$ pip install Django pyecharts 

Django is only available when the virtual environment is active. View installed python libraries, pip list.

(django_pyecharts) PS E:\python_work\Django\django_pyecharts> pip list
Package             Version
------------------- -------
asgiref             3.8.1
Django              5.0.3
djangorestframework 3.15.1
Jinja2              3.1.3
MarkupSafe          2.1.5
pip                 22.3
prettytable         3.10.0
pyecharts           2.0.5
setuptools          65.5.0
simplejson          3.19.2
sqlparse            0.4.4
tzdata              2024.1
wcwidth             0.2.13 

Create a new project

django-admin startproject pyecharts_django_demo . 

Don’t forget this period, or you’ll run into some configuration problems when you deploy your application. If you forget this period, delete the files and folders you created (except Django \ _ pyecharts) and rerun the command. Django stores most of the project-related information in a database, so you need to create a database for Django to use.

python manage.py migrate 

Verify that Django created the project correctly. To do this, execute the command runserver.

python manage.py runserver 

Show

Starting development server at http://127.0.0.1:8000/ 

Equivalent

http://localhost:8000/ 

To shut down the server, switch to the terminal window where you executed the runserver command and press Ctrl + C. If the error message That port is already in use appears, execute the command

python manage.py runserver 8001 

Let Diango use another port. You should also have runserver running in the terminal window that you opened earlier. Open another terminal window (or tab) and change to the directory where the manage. Py is located. Activate that virtual environment,

django_pyecharts\Scripts\activate 

Then execute the command start app:

python manage.py startapp demo 

Register the application in the pyecharts \ _ Django \ _ demo/settings. Py.

# pyecharts_django_demo/settings.py
INSTALLED_APPS = [
    'demo',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
] 

Edit the demo/URL s. Py films

# demo/urls.py
from django.urls import include
from django.urls import re_path as url
from . import views

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

Add a ‘demo. URLs’ in the pyecharts \ _ Django \ _ demo/URLs. Py.

from django.contrib import admin
from django.urls import path
from django.urls import include
from django.urls import re_path as url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^demo/', include('demo.urls')) 

Step 1: Copy the pyecharts template. First, create a new templates folder under the demo folder, and copy the pyecharts template. Copy the pyecharts. Render. Templates to the newly created templates folder,

Step 2: Render the chart Save the following code to the demo/views. Py.

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(["shirt", "cardigan", "Chiffon shirt", "Pants", "High heel", "sock"])
        .add_yaxis("MerchantA", [5, 20, 36, 10, 75, 90])
        .add_yaxis("MerchantB", [15, 25, 16, 55, 48, 8])
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-basic example", subtitle="I am the subtitle"))
    )
    return HttpResponse(c.render_embed()) 

Step 3: Run the project

python manage.py runserver 

Access the service by opening http://127.0.0.1:8000/demo it with a browser

Django Front End and Back End Separation Step 0: Create folders, virtual environments, etc. The previous steps are the same as above. Step 1: Create a new Django project

django-admin startproject pyecharts_django_demo .
python manage.py migrate
python manage.py startapp demo 

Register the application in the pyecharts \ _ Django \ _ demo/settings. Py.

# pyecharts_django_demo/settings.py
INSTALLED_APPS = [
    'demo',  # <--- app name
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
] 

Add a ‘demo. URLs’ in the pyecharts \ _ Django \ _ demo/URLs. Py.

# pyecharts_django_demo/urls.py 
from django.contrib import admin
from django.urls import path
from django.urls import include
from django.urls import re_path as url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^demo/', include('demo.urls'))
] 

Edit the demo/URL s. Py file (create one if none exist)

from django.urls import include
from django.urls import re_path as url
from . import views

urlpatterns = [
    url(r'^bar/', views.ChartView.as_view(), name='demo'),
    url(r'^index/', views.IndexView.as_view(), name='demo'),
] 

Step 2 Write the drawing HTML code. First, create a new templates folder under the root directory folder, and create a new index. HTML.

(django_pyecharts) PS E:\python_work\Django\django_pyecharts_demo> ls

    Table of contents: E:\python_work\Django\django_pyecharts_demo

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         2024/3/24     14:08                demo
d-----         2024/3/24      9:43                django_pyecharts
d-----         2024/3/24     14:06                pyecharts_django_demo
d-----         2024/3/24      9:53                templates
-a----         2024/3/24      9:45         131072 db.sqlite3
-a----         2024/3/24      9:45            699 manage.py 

index.html

<!DOCTYPE html>
<html>
<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="bar" style="width:1000px; height:600px;"></div>
    <script>
        var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});

        (
            function () {
                fetchData(chart);
            }
        );

        function fetchData() {.ajax({
                type: "GET",
                url: "http://127.0.0.1:8000/demo/bar",
                dataType: 'json',
                success: function (result) {
                    chart.setOption(result.data);
                }
            });
        }
    </script>
</body>
</html> 

Step 3: Write Django and pyecharts code to render the chart

Note: At present, due to the problem of JSON data type, the data of JSCode type in pyecharts cannot be converted into JSON data format and returned to the front-end page for use. Therefore, try to avoid using JSCode for drawing in the case of using front and back end separation.

Save the following code to the demo/views. Py.

from django.shortcuts import render

# Create your views here.
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

# Create your views here.
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

def bar_base() -> Bar:
    c = (
        Bar()
        .add_xaxis(["shirt", "cardigan", "Chiffon shirt", "Pants", "High heel", "sock"])
        .add_yaxis("MerchantA", [randrange(0, 100) for _ in range(6)])
        .add_yaxis("MerchantB", [randrange(0, 100) for _ in range(6)])
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-basic example", subtitle="I am the subtitle"))
        .dump_options_with_quotes()
    )
    return c

class ChartView(APIView):
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(bar_base()))

class IndexView(APIView):
    def get(self, request, *args, **kwargs):
        return HttpResponse(content=open("./templates/index.html").read()) 

Step 4: Run the project

python manage.py runserver 

Use a browser to open http://127.0.0.1:8000/demo/index to access the service.