我目前正在尝试在我的django应用程序中实现图形。我创建了一个HTML页面,用于显示 views.py 类中的硬编码详细信息。当我加载网页时,我根本看不到图表。以下是我尝试实施图表的方法:
视图
在这个课程中,我正在创建将在图表上显示的视图。我暂时硬编码了一些数据,只是为了让图表运行起来。
User = get_user_model()
#where i am viewing the chart, calling the html page.
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'nutrition/chart.html', {"users": 10})
class ChartData(APIView):
authentication_classes = []
permission_classes = []
#hard-coded data that i am trying to display on the chart
def get(self, request, format=None):
qs_count = User.objects.all().count()
labels = ["Users", "Blue", "Yellow", "Green", "Purple", "Orange"]
default_items = [qs_count, 12, 22, 13, 11, 15]
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
网址
我正在使用网址来显示网页是nutrition/
网址的扩展名。
urlpatterns = [
#url for the webpage to display the chart
url('^chart/$', ChartView.as_view(), name='chart'),
#url to show the data using the django rest_framework
url('^api/chart/data/$', ChartData.as_view()),
HTML
这里我试图显示图表。我从视图类调用变量,并在条形图上绘制它们。
<script>
{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data) {
labels = data.labels
defaultData = data.default
setChart()
},
error: function (error_data) {
console.log("error")
console.log(error_data)
}
})
function setChart() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '# of Votes',
data: defaultData,
}]
},
});
}
{% endblock %}
</script>
{% block body %}
<div class="row">
<div class="container">
<div class="col-sm-12" url-endpoint="'{% url "nutrition:api-data" %}">
<h1>Nutrition Chart</h1>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</div>
</div>
{% endblock body %}
我一直在关注我在这里链接的教程: https://www.youtube.com/watch?v=B4Vmm3yZPgc
修改
答案 0 :(得分:0)
您是否尝试在HTML中使用var endpoint ='api / chart / data /'而不是var endpoint ='/ api / chart / data /'?