Django 기반 빠 른 통합 Echarts 코드 예제
https://echarts.apache.org/zh/builder.html
2.django 프로젝트 를 만 들 거나 기 존 프로젝트 를 만 듭 니 다.
test.html 파일
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>ECharts</title>
  <!--    echarts.js -->
  {% load static %}
  <script src="{% static '/js/echarts.min.js' %}"></script>
</head>
<body>
  <!--  ECharts        (  ) Dom -->
  <div id="main" style="width: 600px;height:400px;"></div>
  <script type="text/javascript">
    //       dom,   echarts  
    var myChart = echarts.init(document.getElementById('main'));
    //            
    var option = {
      title: {
        text: 'ECharts     '
      },
      tooltip: {},
      legend: {
        data:['  ']
      },
      xAxis: {
        data: ["  ","   ","   ","  ","   ","  "]
      },
      yAxis: {},
      series: [{
        name: '  ',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20]
      }]
    };
    //                 。
    myChart.setOption(option);
  </script>
</body>
</html>url 파일
from django.urls import path
from app.views import TestView
urlpatterns = [
  path('test/',TestView.as_view()),
]뷰 파일
from django.shortcuts import render
from rest_framework.views import View
from rest_framework.response import Response
class TestView(View):
  def dispatch(self, request, *args, **kwargs):
    """
          ,    dispatch  ,dispatch             get/post/put   
      :APIView  dispatch          
    """
    return super().dispatch(request, *args, **kwargs)
  def get(self, request, *args, **kwargs):
    return render(request, "test.html")
  def post(self, request, *args, **kwargs):
    return Response('POST  ,    ')
  def put(self, request, *args, **kwargs):
    return Response('PUT  ,    ')
Views  URL 주소:
 django 데이터베이스 에 있 는 데 이 터 를 가 져 와 echarts 에 전달 합 니 다.
test1.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>ECharts</title>
  <!--    echarts.js -->
  {% load static %}
  <script src="{% static '/js/echarts.min.js' %}"></script>
</head>
<body>
  <div id="main" style="width: 600px;height:400px;"></div>
  <script type="text/javascript">
  //       dom,   echarts  
  console.log(name)
  var myChart = echarts.init(document.getElementById('main'));
  //            
  var option = {
    title: {
      text: 'ECharts     '
    },
    tooltip: {},
    legend: {
      data: ['  ']
    },
    xAxis: {
      data: {{ name|safe }}
    },
    yAxis: {},
    series: [{
      name: '  ',
      type: 'bar',
      data:{{ data|safe }}
    }]
  };
  //                 。
  myChart.setOption(option);
  </script>
</body>
</html>url 파일
from django.urls import path
from app.views import TestView1
urlpatterns = [
  path('test1/',TestView1.as_view()),
]뷰 파일
from django.shortcuts import render
from rest_framework.views import View
from rest_framework.response import Response
class TestView1(View):
  def dispatch(self, request, *args, **kwargs):
    """
          ,    dispatch  ,dispatch             get/post/put   
      :APIView  dispatch          
    """
    return super().dispatch(request, *args, **kwargs)
  def get(self, request, *args, **kwargs):
    name = ["  ","   ","   ","  ","   ","  "]
    data = [56, 40, 54, 23, 12, 31]
    return render(request, "test1.html",{"name":name,"data":data})
  def post(self, request, *args, **kwargs):
    return Response('POST  ,    ')
  def put(self, request, *args, **kwargs):
    return Response('PUT  ,    ')메모:views 파일 에서 데 이 터 를 직접 되 돌려 줍 니 다.html 템 플 릿 에서 라벨 렌 더 링 을 사용 합 니 다.만약 에 ORM 을 사용 하여 데이터 베 이 스 를 가 져 올 필요 가 있다 면 다음 과 같은 작업 을 할 수 있 습 니 다.wheelsList = Wheel.objects.all()
name = list(Wheel.objects.values_list('name', flat=True))
data = list(Wheel.objects.values_list('trackid', flat=True))
URL 주소:
 echarts 비동기 업데이트 데이터
test2.html 파일
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <!--    jquery.js-->
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <!--    echarts.js -->
  {% load static %}
  <script src="{% static '/js/echarts.min.js' %}"></script>
</head>
<body>
  <div id="main" style="width: 600px;height:400px;"></div>
  <script type="text/javascript">
  $(function () {
    var server_info;
    var myChart = echarts.init(document.getElementById('main'));
    var option = {
      title: {
        text: 'ECharts     '
      },
      tooltip: {},
      legend: {
        data:['  ']
      },
      xAxis: {
        data: {{ name | safe }}
      },
      yAxis: {},
      series: [{
        name: '  ',
        type: 'bar',
        data: {{ data | safe }}
      }]
    };
    myChart.setOption(option, true);
    setInterval( function () {
        $.ajax({
          type: 'GET',
          url: '/test1_api/',
          dataType: 'json',
          success: function (arg) {
            server_info = eval(arg);
            option.xAxis.data = server_info.name;
            option.series[0].data = server_info.data;
          }
        });
          myChart.setOption(option, true);
        }, 2000);
     window.onresize = function () {
      myChart.resize();
    };
  });
  </script>
</body>
</html>url 파일
from django.urls import path
from app.views import TestView,TestView1,TestView1api
urlpatterns = [
  path('test2/',TestView1.as_view()),
  path('test1_api/',TestView1api.as_view()),
]파일 보기
from django.shortcuts import render
from rest_framework.views import View
from rest_framework.response import Response
from django.http import HttpResponse
class TestView1(View):
  def dispatch(self, request, *args, **kwargs):
    """
          ,    dispatch  ,dispatch             get/post/put   
      :APIView  dispatch          
    """
    return super().dispatch(request, *args, **kwargs)
  def get(self, request, *args, **kwargs):
    name = ["  ","   ","   ","  ","   ","  "]
    data = [56, 40, 54, 23, 12, 31]
    return render(request, "test2.html",{"name":name,"data":data})
  def post(self, request, *args, **kwargs):
    return Response('POST  ,    ')
  def put(self, request, *args, **kwargs):
    return Response('PUT  ,    ')
count = 1
class TestView1api(View):
  def dispatch(self, request, *args, **kwargs):
    """
          ,    dispatch  ,dispatch             get/post/put   
      :APIView  dispatch          
    """
    return super().dispatch(request, *args, **kwargs)
  def get(self, request, *args, **kwargs):
    global count
    name = ["  ","   ","   ","  ","   ","  "]
    data = [56+count, 40+count, 54+count, 23+count, 12+count, 31+count]
    count = count + 1
    print(data)
    print(count)
    ret = {'name': name, 'data': data}
    return HttpResponse(json.dumps(ret))
  def post(self, request, *args, **kwargs):
    return Response('POST  ,    ')
  def put(self, request, *args, **kwargs):
    return Response('PUT  ,    ')
 echarts 비동기 로드+비동기 업데이트
지난 예 시 를 바탕 으로 test 2.html 를 다음 과 같이 수정 합 니 다.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <!--    jquery.js-->
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <!--    echarts.js -->
  {% load static %}
  <script src="{% static '/js/echarts.min.js' %}"></script>
</head>
<body>
  <div id="main" style="width: 600px;height:400px;"></div>
  <script type="text/javascript">
  $(function () {
    var server_info;
    //       dom,   ECharts  
    var myChart = echarts.init(document.getElementById('main'));
    //            
    var option = {
      title: {
        text: 'ECharts     '
      },
      tooltip: {},
      legend: {
        data: ['  ']
      },
      xAxis: {
        data: []
      },
      yAxis: {},
      series: [{
        name: '  ',
        type: 'bar',
        data: []
      }]
    };
    myChart.setOption(option, true);
    //     json    
    $.getJSON('http://127.0.0.1:8080/test1_api/', function (data) {
      myChart.setOption({
        xAxis: {
          data: data.name
        },
        series: [{
          //             
          data: data.data
        }]
      });
    });
    // ajax    json    
    setInterval( function () {
        $.ajax({
          type: 'GET',
          url: '/test1_api/',
          dataType: 'json',
          success: function (arg) {
            server_info = eval(arg);
            option.xAxis.data = server_info.name;
            option.series[0].data = server_info.data;
          }
        });
          myChart.setOption(option, true);
        }, 2000);
     window.onresize = function () {
      myChart.resize();
     };
  });
  </script>
</body>
</html>이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django 라우팅 계층 URLconf 작용 및 원리 해석URL 구성(URLconf)은 Django가 지원하는 웹 사이트의 디렉토리와 같습니다.그것의 본질은 URL과 이 URL을 호출할 보기 함수 사이의 맵표입니다. 위의 예제에서는 URL의 값을 캡처하고 위치 매개 변수로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.