【问题标题】:Passing Django data to Highcharts via JSON通过 JSON 将 Django 数据传递给 Highcharts
【发布时间】:2018-02-13 14:44:00
【问题描述】:

更新:

我一直在尝试复制this solution thread 中使用的方法以通过 Django 显示 Highcharts 图表,但徒劳无功。我正在将数据从 python 脚本传递到我的 views.py 文件,但图表没有显示出来。

以下是我在浏览器中查看查看源代码时得到的结果。我在这个 html 文档中缺少什么?图表未显示。

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Head title here</title>
    <meta charset="utf-8" />

    <link rel="stylesheet" href="/static/css/bootstrap.min.css" type = "text/css"/>
    <meta name="viewport" content = "width=device-width, initial-scale=1.0">

    <style type="text/css">
        html,
        body {
          height:100%
        }
    </style>
</head>

<body class="body" style="background-color:#f6f6f6">
    <div class="container-fluid" style="min-height:95%; ">
        <div class="row">
              <div class="col-sm-2">
                  <br>
                  <center>
                    <img src="/static/img/profile.jpg" class="responsive-img" style='max-height:100px;' alt="face">
                  </center>
              </div>
              <div class="col-sm-10">
                  <br>
                  <center>
                  <h3>Some stuff goes here</h3>
                  </center>
              </div>
        </div><hr>

        <div class="row">
          <div class="col-sm-2">
          <br>

          <br>
            <!-- Great, til you resize. -->
            <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">-->
            <div class="well bs-sidebar" id="sidebar" style="background-color:#fff">
              <ul class="nav nav-pills nav-stacked">
                <li><a href='/'>Home</a></li>
                <li><a href='/blog/'>Blog</a></li>
                <li><a href='/contact/'>Contact</a></li>
              </ul>
            </div> <!--well bs-sidebar affix-->
          </div> <!--col-sm-2-->
          <div class="col-sm-10">

            <div class='container-fluid'>
            <br><br>

<body>
    <div id="chart_ID" class="chart" style="height:100px; width:100%"></div>
</body>

            </div>
          </div>
        </div>
    </div>
</body>

</html>

原帖:

我的 my-app/views.py 文件

from __future__ import unicode_literals
import datetime
from django.shortcuts import render
from . import python_script

def plot(request, chartID = 'chart_ID', chart_type = 'bar', chart_height = 500):

    data = python_script.chart_function()
    categories = python_script.chart_categories()
    chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,}
    title = {"text": 'my title here'}
    xAxis = {"title": {"text": 'axis title here'}, "categories": categories}
    yAxis = {"title": {"text": 'axis title here'}}
    series = [
        {"name": 'Asia Pacific', "data": data['Asia Pacific']},
        {"name": 'CIS', "data": data['Commonwealth of Independent States']},
        {"name": 'Europe', "data": data['Europe']},
        {"name": 'Latin America', "data": data['Latin America']},
        {"name": 'MENA', "data": data['Middle East and North Africa']},
        {"name": 'Northern America', "data": data['Northern America']},
        {"name": 'SSA', "data": data['Sub-Saharan Africa']}
    ]

    return render(request, 'my-app/chart.html', {'chartID': chartID, 'chart': chart,
                                                'series': series, 'title': title,
                                                'xAxis': xAxis, 'yAxis': yAxis})

在我的views.py文件中:

  • data 的格式是一个字典:{'Asia Pacific':[1,2,3,4],'Europe':[1,2,3...], . ..}
  • categories 的格式是字符串列表:['A', 'B', ...]

我的 my-app/chart.html 文件

{% load compress %}
{% compress js %}
<script src="{{ STATIC_URL }}jquery-3.2.1.js"></script>
<script src="{{ STATIC_URL }}jquery-3.2.1.min.js"></script>
<script src="{{ STATIC_URL }}Highcharts-5.0.14/code/js/highcharts.js"></script>
<script src="{{ STATIC_URL }}Highcharts-5.0.14/code/js/modules/exporting.js"></script>
{% endcompress %}

{% block heading %}
    <h1 align="center">Analysis</h1>
{% endblock %}

{% block content %}
    <div id={{ chartID|safe }} class="chart" style="height:100px; width:100%"></div>
{% endblock %}

{% block overwrite %}
<!-- Overwrite the base.html jQuery load and put in head for Highcharts to work -->
{% endblock %}

{% block extrajs %}
<!-- Maps the Python template context variables from views.py to the Highchart js variables -->
<script>
    var chart_id = {{ chartID|safe }}
    var chart = {{ chart|safe }}
    var title = {{ title|safe }}
    var xAxis = {{ xAxis|safe }}
    var yAxis = {{ yAxis|safe }}
    var series = {{ series|safe }}
</script>

<!-- Highchart js. Variable map shown above -->
<script>
$(document).ready(function() {
    $(chart_id).highcharts({
        chart: chart,
        title: title,
        xAxis: xAxis,
        yAxis: yAxis,
        series: series
    });
});
</script>
{% endblock %}

我的 my-app/urls.py 文件

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$',views.index, name='index'),
    url(r'^graph/', views.plot, name = 'plot'),
]

我的 settings.py 文件

INSTALLED_APPS = [
    'my-app',
    'highcharts',
    'jquery',
    'compressor',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
...
STATIC_ROOT = 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'

我已经运行了命令 python manage.py collectstatic

【问题讨论】:

    标签: python json django highcharts


    【解决方案1】:

    在模板中直接渲染 Python 数据结构(如列表和字典)以在 JavaScript 中使用它们可以工作,但不可靠。相反,在您的视图中将它们转换为 JSON:

    import json
    ...
    return render(request, 'my-app/chart.html',
                  {'chartID': json.dumps(chartID), 'chart': json.dumps(chart),
                   'series': json.dumps(series), 'title': json.dumps(title),
                   'xAxis': json.dumps(xAxis), 'yAxis': json.dumps(yAxis)})
    

    在您的模板中,像这样使用 JSON:

    var chartID = JSON.parse("{{ chartID|escapejs }}")
    

    如果这不能解决问题,请检查浏览器的 JavaScript 控制台是否有错误消息。

    【讨论】:

    • 谢谢丹尼尔 - 它没有解决它,但我检查了 JavaScript 控制台,它确实为我正在加载的每个静态文件显示 4 个警报,警报说:Uncaught SyntaxError: Unexpected token
    • 显然您的静态文件不包含有效的 JavaScript,这听起来像文件无法正确加载。检查页面源中的 URL 并查看它返回的内容。
    • 顺便说一句,用这些发现更新您的原始问题是个好主意,这样其他人就可以更容易地跟进和加入。
    • 谢谢丹尼尔 - 你是对的,在查看源代码中,页面显示的代码与上面 chart.html 文件中的代码完全相同。第一行是 。它似乎没有将页面解释为
    • 我刚刚意识到您的模板可能扩展了另一个模板,但在第一个模板中缺少{% extends ... %} 标签。
    猜你喜欢
    • 2015-03-04
    • 2010-11-29
    • 2012-10-27
    • 2015-06-21
    • 1970-01-01
    • 2018-09-27
    • 2012-01-03
    • 2012-11-13
    相关资源
    最近更新 更多