django-chartjs 问题。图表未显示在页面上

问题描述 投票:0回答:0

我目前正在尝试在我的 django 应用程序中显示一个条形图,该图表应该代表我在数据库中拥有的所有医院的总死亡率。当我在浏览器中键入 url 或在控制台中打印时,我可以看到数据,并且我得到了我期望的输出。现在的问题是图表没有显示在页面布局上,我没有收到任何错误或警告。我这里有代码

window.addEventListener('DOMContentLoaded', () => {
  // Get the data from the server
fetch('/measures_data')
.then(response => response.json())
.then(data => {
  // Process the data to get the mortality rates by hospital
  console.log(data)
  const labels = [];
  const mortalityRates = [];
  data.forEach(measure => {
    labels.push(measure.hospital__name);
    mortalityRates.push(measure.total_mortality_rate);
  });
  
  // Create a bar chart
  const ctx = document.getElementById('motalityRate').getContext('2d');
  const chart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Total Mortality Rate',
        data: mortalityRates,
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 1
      }],
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
});
})
views.py 

@require_http_methods(['GET'])
def measures_data(request):
    measures = Measures.objects.values('hospital__name').annotate(
        total_mortality_rate=Sum('mortality_rate')
    ).order_by('hospital__name')
    return JsonResponse(list(measures), safe=False)
{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="{% static '/dashboard/css/index.css' %}" />
    <title>Dashboard</title>
  </head>
  
  
  <body>
    <div class="chart census">
              <h3 class="title">Mortality rate</h3>
              <canvas id="motalityRate"></canvas>
    </div>
    
     <script type="text/javascript" src="{% static '/dashboard/js/main.js' %}"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script type="text/javascript" src="{% static 'js/Chart.min.js' %}"></script>
   </body>

我尝试使用 chartjs CDN 库,但仍然无法正常工作。如有任何帮助,我们将不胜感激

javascript python html django chart.js
© www.soinside.com 2019 - 2024. All rights reserved.