【问题标题】:charts.js not loading in Djangochart.js 未在 Django 中加载
【发布时间】:2023-03-30 21:17:01
【问题描述】:

我正在使用 charts.js 在 django 中制作图表。我的 index.html 加载但图表未加载。我不知道为什么它不起作用。我正在使用pipenv shell 制作虚拟环境,但由于某种原因仍然没有运气。我有我的静态文件夹,里面有我的main.js,这就是生成图表的原因。我的网址很好,因为它显示了我的<h1> 标签,但没有图表。在我的终端中,我确实看到了"GET /static/main.js HTTP/1.1" 304 0

索引.HTML

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
    <script type="text/javascript" src="{% static 'main.js' %}"></script>
    
</head>

<body>
<h1>index</h1>
<canvas id="myChart"></canvas>
</body>
</html>

MAIN.JS

let labels1 = ["YES", "NO"];
let data1 = [50,50];
let colors1 = ['#49A9EA', '#36CAAB'];


let myChart1 = document.getElementByID("myChart").getContext('2d');

let chart1 = new Chart(myChart1), {
    type; 'doughnut',
    data: {
        labels: labels1,
        datasets: [{
            data: data1,
            backgroundColor: colors1
            }]
    },
    options: {
        title: {
            text: "DO YOU LIKE DOUGHNUTS?"
            display: true;

        }
    }
});

URLS.PY

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name="index")
]

【问题讨论】:

    标签: javascript python django chart.js


    【解决方案1】:

    那是因为您的canvas 元素尚未加载,请将您的main.js 代码包装在DOMContentLoaded 回调函数中

    document.addEventListener('DOMContentLoaded', function(){ 
        // wrap your js code here
    }, false);
    
    // with jQuery 
    $(document).ready(function(){ /* ... */ });
    
    // shorter
    $(function(){ /* ... */ });
    

    更新

    还要检查你的 js 代码

    let ctx = document.getElementById('pie-chart').getContext('2d');
    let chart1 = new Chart(ctx, config);
    
    

    【讨论】:

    • 我仍然得到相同的结果。
    • @pete800 看来你在你的js代码中,不小心在myChart1之后添加了一个')'let chart1 = new Chart(myChart1), config),图表需要两个参数,context, config
    • 那是个好地方,谢谢。不幸的是仍然没有加载。
    • @pete800 为画布指定heightwidth 然后检查文档如果您遗漏了什么,我找不到其他错误。 chartjs.org/docs/latest
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2018-03-03
    • 1970-01-01
    • 2011-08-02
    • 2013-03-13
    • 1970-01-01
    • 2021-08-25
    • 2020-08-23
    相关资源
    最近更新 更多