JS脚本未包含在Django项目中
我正在学习Django,遇到了一个问题。我的JS脚本没有包含在Django项目里。路径是正确的,页面本身有图表的部分可以正常工作,但圆形图或柱状图的输出却没有显示出来。
index.html
{% extends 'partials/base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<div class="row ">
<div class="col-md-6 my-4">
<div class="bg-white">
<div class="card-body">
<canvas id="myChart1" width="400" height="300"></canvas>
<script src="{% static 'main.js' %}"></script>
</div>
</div>
</div>
<div class="col-md-6 my-4">
<div class="bg-white">
<div class="card-body">
<canvas id="myChart" width="400" height="300"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [{% for order in order %} '{{order.name}}',{% endfor %}],
datasets: [{
label: 'Orders',
data: [{% for order in order %} {{ order.order_quantity }}, {% endfor %}],
backgroundColor: [
'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)'
],
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
}
}]
}
}
});
</script>
</div>
</div>
</div>
</div>
{% endblock %}
base.html
<!--Chartjs CDN-->
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<!--Custome CSS-->
<link rel="stylesheet" href="/css/style.css">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
{% include 'partials/nav.html' %}
{% include 'partials/topnav.html' %}
<div class="container">
{% block content %}
{% endblock %}
</div>
<!-- Optional JavaScript; choose one of the two! -->
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = (BASE_DIR/"media/")
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
我尝试把JS脚本放到一个单独的文件里,但还是不行。你们有什么办法解决这个问题吗?
1 个回答
0
确保运行 python3 manage.py collectstatic
这个命令,让Django把你项目中的文件收集起来。