我正在修改我的Wagtail应用程序的主仪表板,以提供更有用/相关的数据,如开放工作订单的数量或客户数量。
让我的Chart.js显示在我的仪表板上有一些困难。我已经确认资源chart.js (Version2.8.0)正在加载,我的画布元素也被加载到页面上。不过,图表不会显示。
这是一些密码。这都在我的“仪表板”应用程序中。
wagtail_hooks.py
class WelcomePanel:
order = 5000
def __init__(self, request):
self.request = request
self.logged_in_user = request.user.username
def render(self):
return render_to_string('wagtailadmin/dashboard.html', {
'logged_in_user': self.logged_in_user,
}, request=self.request)
# simply pass the 'request' to the panel
@hooks.register('construct_homepage_panels')
def add_another_welcome_panel(request, panels):
panels.append(WelcomePanel(request))templates/wagtailadmin/dashboard.html
{% load static %}
<h1> This text is visible </h1>
<canvas id="pie_chart" height="604" width="1210" style="display: block; width: 605px; height: 302px;"></canvas>
<script src="{% static 'js/chart.js' %}" type="text/javascript"><script>
<script tyle="text/javascript">
var stars = [135850, 52122, 148825, 16939, 9763];
var frameworks = ["React", "Angular", "Vue", "Hyperapp", "Omi"];
document.addEventListener('DOMContentLoaded', function() {
var ctx = document.getElementById("pie_chart").getContext('2d');
var myChart = new Chart(ctx, {
type: "pie",
data: {
labels: frameworks,
datasets: [
{
label: "Github Stars",
data: stars,
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)"
],
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)",
],
borderWidth: 1
}
]
}
});
}, false);
</script>编辑我尝试设置async defer以及事件侦听器,只在DOM完全加载DOMContentLoaded时才执行图表创建。
发布于 2020-12-21 01:46:59
我还没有在本地运行这段代码,但这只是一个快速的建议--您可能需要等到加载DOM后才能运行getElementById和new Chart部件。
这是因为在页面完全呈现之前,文档查询将不返回任何内容。
<script tyle="text/javascript">
// note: you can set up your stars/frameworks and other data outside of the callback below
// the key thing is that the DOM writing and dom query (getElementById) are inside the callback
document.addEventListener('DOMContentLoaded', function() {
var ctx = document.getElementById("pie_chart");
var myChart = new Chart( /* ... code here */);
}, false);
</script>您可以在这里阅读更多关于这一点的信息:https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
这里有一个这样的问题,也是https://stackoverflow.com/a/11936919/8070948
https://stackoverflow.com/questions/65386528
复制相似问题