图表未显示在Django应用程序的Web页面上(使用Chart.js)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图表未显示在Django应用程序的Web页面上(使用Chart.js)相关的知识,希望对你有一定的参考价值。

我是Web开发的新手,我在django项目的前端工作。我有一个从引导程序获得的仪表板模板,我想集成我用chart.js制作的图表。

这些图表在另一个项目中工作正常,但是当它是仪表板的一部分时,我无法显示任何东西。

我附上了我的index.htmlplot.html以及我要绘制的数据示例以及在Chrome控制台中收到的错误

<!DOCTYPE html>
<html lang="en">


{% load static %}

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>SB Admin 2 - Dashboard</title>

  <!-- Custom fonts for this template-->
  <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet"  type="text/css">
  <link href="{% static  'https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i' %}" rel="stylesheet">

  <!-- Custom styles for this template-->
  <link href="{%  static 'css/sb-admin-2.min.css' %}" rel="stylesheet">

</head>

<body id="page-top">

  <!-- Page Wrapper -->
  <div id="wrapper">

    <!-- Sidebar -->
    <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

      <!-- Sidebar - Brand -->
      <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
        <div class="sidebar-brand-icon rotate-n-15">
          <i class="fas fa-laugh-wink"></i>
        </div>
        <div class="sidebar-brand-text mx-3"> Inventory Management <sup></sup></div>
      </a>

      <!-- Divider -->
      <hr class="sidebar-divider my-0">

      <!-- Nav Item - Dashboard -->
      <li class="nav-item active">
        <a class="nav-link" href="index.html">
          <i class="fas fa-fw fa-tachometer-alt"></i>
          <span>Dashboard</span></a>
      </li>


      <!-- Divider -->
      <hr class="sidebar-divider">

      <!-- Heading -->
      <div class="sidebar-heading">
        Demand Planning
      </div>

      <!-- Nav Item - Pages Collapse Menu -->
      <li class="nav-item">
        <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
          <i class="fas fa-fw fa-cog"></i>
          <span>Items</span>
        </a>
        <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
          <div class="bg-white py-2 collapse-inner rounded">
            <h6 class="collapse-header">Custom Components:</h6>
            <a class="collapse-item" href="buttons.html">Buttons</a>
            <a class="collapse-item" href="cards.html">Cards</a>
          </div>
        </div>
      </li>

      <!-- Nav Item - Utilities Collapse Menu -->
      <li class="nav-item">
        <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true" aria-controls="collapseUtilities">
          <i class="fas fa-fw fa-wrench"></i>
          <span>Suppliers</span>
        </a>
        <div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
          <div class="bg-white py-2 collapse-inner rounded">
            <h6 class="collapse-header">Custom Utilities:</h6>
            <a class="collapse-item" href="utilities-color.html">Colors</a>
            <a class="collapse-item" href="utilities-border.html">Borders</a>
            <a class="collapse-item" href="utilities-animation.html">Animations</a>
            <a class="collapse-item" href="utilities-other.html">Other</a>
          </div>
        </div>
      </li>

      <!-- Divider -->
      <hr class="sidebar-divider">

      <!-- Divider -->
      <hr class="sidebar-divider d-none d-md-block">

      <!-- Sidebar Toggler (Sidebar) -->
      <div class="text-center d-none d-md-inline">
        <button class="rounded-circle border-0" id="sidebarToggle"></button>
      </div>

    </ul>
    <!-- End of Sidebar -->

    <!-- Content Wrapper -->
    <div id="content-wrapper" class="d-flex flex-column">

      <!-- Main Content -->
      <div id="content">

        <!-- Topbar -->
        <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

          <!-- Sidebar Toggle (Topbar) -->
          <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
            <i class="fa fa-bars"></i>
          </button>

          <!-- Topbar Search -->
          <form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
            <div class="input-group">
              <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
              <div class="input-group-append">
                <button class="btn btn-primary" type="button">
                  <i class="fas fa-search fa-sm"></i>
                </button>
              </div>
            </div>
          </form>

          <!-- Topbar Navbar -->
          <ul class="navbar-nav ml-auto">

            <!-- Nav Item - Search Dropdown (Visible Only XS) -->
            <li class="nav-item dropdown no-arrow d-sm-none">
              <a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-search fa-fw"></i>
              </a>
              <!-- Dropdown - Messages -->
              <div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown">
                <form class="form-inline mr-auto w-100 navbar-search">
                  <div class="input-group">
                    <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
                    <div class="input-group-append">
                      <button class="btn btn-primary" type="button">
                        <i class="fas fa-search fa-sm"></i>
                      </button>
                    </div>
                  </div>
                </form>
              </div>
            </li>
            <!-- Nav Item - User Information -->
            <li class="nav-item dropdown no-arrow">
              <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <span class="mr-2 d-none d-lg-inline text-gray-600 small">Valerie Luna</span>
                <img class="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60">
              </a>
              <!-- Dropdown - User Information -->
              <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
                <a class="dropdown-item" href="#">
                  <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
                  Profile
                </a>
                <a class="dropdown-item" href="#">
                  <i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
                  Settings
                </a>
                <a class="dropdown-item" href="#">
                  <i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>
                  Activity Log
                </a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
                  <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                  Logout
                </a>
              </div>
            </li>

          </ul>

        </nav>
        <!-- End of Topbar -->

        <!-- Begin Page Content -->
        <div class="container-fluid">

          <!-- Page Heading -->
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
            <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
          </div>

          <!-- Content Row -->
          <div class="row">

            <!-- Earnings (Monthly) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Item in stock alerte</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-calendar fa-2x text-gray-300"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Earnings (Monthly) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-success text-uppercase mb-1">items in negative safety stock</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Pending Requests Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">items in alerte service level</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800">18</div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-comments fa-2x text-gray-300"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
            <!-- attempt to make a bar graph on the page -->

            <div class="card shadow mb-4">
                <div class="card-header py-3">

                  <h6 class="m-0 font-weight-bold text-primary">Top Seller</h6>
                </div>
                <div class="card-body">
                <script>
                    $(document).ready(function() {
                        {% block jquery %}

                        {% endblock %}
                    })

                  </script>
                  <div class="chart-bar">
                      {% block content %}
                      {% endblock content %}
                  </div>
                  <hr>
{#                  Styling for the bar chart can be found in the <code>/js/demo/chart-bar-demo.js</code> file.#}
                </div>
              </div>
            </div>




          <!-- Content Row -->
          <div class="row">

            <!-- Content Column -->
            <div class="col-lg-6 mb-4">

        <!-- /.container-fluid -->

      </div>
      <!-- End of Main Content -->

      <!-- Footer -->
      <footer class="sticky-footer bg-white">
        <div class="container my-auto">
          <div class="copyright text-center my-auto">
            <span>Copyright &copy; Your Website 2019</span>
          </div>
        </div>
      </footer>
      <!-- End of Footer -->

    </div>
    <!-- End of Content Wrapper -->

  </div>
  <!-- End of Page Wrapper -->

  <!-- Scroll to Top Button-->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <!-- Logout Modal-->
  <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
          <button class="close" type="button" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
        <div class="modal-footer">
          <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
          <a class="btn btn-primary" href="login.html">Logout</a>
        </div>
      </div>
    </div>
  </div>

    <!-- Bootstrap core javascript-->
  <script src="{% static '/vendor/jquery/jquery.js' %}"></script>

  <script src="{% static '/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>

  <!-- Core plugin JavaScript-->
  <script src="{% static '/vendor/jquery-easing/jquery.easing.min.js' %}"></script>

  <!-- Custom scripts for all pages-->
  <script src="{% static 'js/sb-admin-2.js' %}"></script>

  <!-- Page level plugins -->
  <script src="{% static '/vendor/chart.js/Chart.js' %}"></script>

  <!-- Page level custom scripts -->
</body>

</html>

plot.html

%  extends 'dashboard/index.html' %}
<script>
{% block jquery %}
var endpoint = '/api/chart/data'
var defaultData4 = []
var labels4 = []
;

$.ajax({
    method: "GET",
    url: endpoint,
    success: function(data){

        labels4 = data.labels4
        defaultData4 = data.default4
        setChart()
    },
    error: function(error_data){

        console.log(error_data)
    }}
)

function setChart(){
    var ctx4 = document.getElementById('myChart4').getContext('2d');


    var myChart4 = new Chart(ctx4, {
        type: 'bar',
        data: {
            labels: labels4,
            datasets: [{
                label: 'top sellers',
                data: defaultData4,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }],
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        }
    })

}

{% endblock %}
</script>
{%  block content %}
<div class ='row'>
    <div class="clo-sm-12">
        <h1>Inventory Management Dashboard</h1>
        <canvas id="myChart4" width="100" height="20"></canvas>
    </div>
</div>

{% endblock content %}
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "labels4": [
        "108951",
        "115510",
        "118301",
        "118360",
        "118740",
        "118908",
        "128245",
        "128715",
        "269562",
        "269945",
        "282020",
        "284600",
        "289217",
        "289225",
        "289226"
    ],
    "default4": [
        1633.2774193548387,
        1015.5128205128206,
        671.0392156862745,
        2421.108108108108,
        930.4,
        958.5,
        521.1617647058823,
        2142.0,
        9040.0,
        625.3037974683544,
        516.5,
        2045.4548387096775,
        413.06666666666666,
        363.06451612903226,
        300.0
    ]
}

图像:

enter image description here

我不太确定该代码有什么问题,我不知道为什么会这样。

答案

我无法重现该问题。似乎您的代码/环境中有某些东西阻止了它们的融合。

请参见下面的工作演示

主持人] >>

我在这里发布我的代码,供OP查看,看看是否可以在我的工作版本与他们的工作版本之间发现错误。OP确认问题后,如有必要,我可以删除此答案。

$(function() {
  var endpoint = 'https://jsonplaceholder.typicode.com/todos';
  
  var dataObj = {
    "labels4": [
        "108951",
        "115510",
        "118301",
        "118360",
        "118740",
        "118908",
        "128245",
        "128715",
        "269562",
        "269945",
        "282020",
        "284600",
        "289217",
        "289225",
        "289226"
    ],
    "default4": [
        1633.2774193548387,
        1015.5128205128206,
        671.0392156862745,
        2421.108108108108,
        930.4,
        958.5,
        521.1617647058823,
        2142.0,
        9040.0,
        625.3037974683544,
        516.5,
        2045.4548387096775,
        413.06666666666666,
        363.06451612903226,
        300.0
    ]
};

  $.ajax({
    method: "GET",
    url: endpoint,
    success: function(data) {
      console.log('data received');
      // now let's use the mocked data above instead
      labels4 = dataObj.labels4
      defaultData4 = dataObj.default4
      setChart()
    },
    error: function(error_data) {

      console.log(error_data)
    }
  });


  function setChart() {
    var ctx4 = document.getElementById('myChart4').getContext('2d');

    var myChart4 = new Chart(ctx4, {
      type: 'bar',
      data: {
        labels: labels4,
        datasets: [{
          label: 'top sellers',
          data: defaultData4,
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }],
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      }
    })
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>


<div class='row'>
  <div class="col-sm-12">
    <h1>Inventory Management Dashboard</h1>
    <canvas id="myChart4" width="100" height="20"></canvas>
  </div>
</div>

以上是关于图表未显示在Django应用程序的Web页面上(使用Chart.js)的主要内容,如果未能解决你的问题,请参考以下文章

Django 应用程序未在管理页面中显示注册模型

在 django 上运行的 Python Web 应用程序,cPanel 显示错误:找不到页面

如何使用 web 视图(chart.js)在 android 电视中显示图表

图像未显示在 Django 应用程序上

Summernote 编辑器未在 django 管理页面上显示任何内容

Django + iis 上传文件时发生未显示页面,因为请求实体过大