javascript - django 中的 Highcharts

标签 javascript django highcharts django-templates

我是 django 的新手。我想在 django 中使用 highcharts 来绘制图表。我所做的是创建了一个名为 Telecom 的项目。然后我将 highcharts 文件放在文件夹 Telecom/media/highcharts 中。我在 Telecom/media/js 位置写了一个文件 script.js。

脚本.js

$(function () {
        $('#container').highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: 'Monthly Average Rainfall'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                categories: [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ]
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Rainfall (mm)'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                    '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: 'Tokyo',
                data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]

            }, {
                name: 'New York',
                data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]

            }, {
                name: 'London',
                data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]

            }, {
                name: 'Berlin',
                data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]

            }]
        });
    });

还有 Telecom/templates/welcome/higraph.html

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="http://code.highcharts.com/highcharts.js"></script>

        <script type = "text/javascript" src = "script.js"> 
        </script>
    </head>

    <body>
        <div id="container" style="width:50%; height:400px; float:right;">
        </div>
    </body>

</html>

设置.py

DEBUG = True
TEMPLATE_DEBUG = DEBUG

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

PROJECT_DIR = os.path.dirname(__file__)

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)


MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'telecom_db',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

ALLOWED_HOSTS = []

TIME_ZONE = 'America/Chicago'

LANGUAGE_CODE = 'UTC'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

MEDIA_ROOT = os.path.join(PROJECT_DIR,'..', 'media')

MEDIA_URL = 'http://localhost:8000/media/'

STATIC_ROOT = ''

STATIC_URL = '/static/'

ADMIN_MEDIA_PREFIX = '/media/admin/'

# Additional locations of static files
STATICFILES_DIRS = (

)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b9_hyqe*b&ra_&wlm5a9xas_ag#5mjv-dy=to%hdk_u-#xvn*l'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#    'django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (       
                  os.path.join(PROJECT_DIR, '..','templates'),
#                  os.path.join(PROJECT_DIR, 'templates/welcome'),
)


MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'Telecom.urls'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.admin',

    'django.contrib.admindocs',
    'welcome',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

但是图表没有显示,如何让它工作?

最佳答案

您的程序需要互联网才能显示图形,因为 .js 文件位置来自 url。如果您想离线加载图形,请下载所需的库(js 文件)并进行如下更改。

settings.py #update static root 和 url

STATIC_ROOT = ''
STATIC_URL = '/static/'

现在将您的 .js(源文件)放入在您的应用程序文件夹中创建的静态文件夹中。

现在在模板中加载 .js 文件,方法是将下面的代码放在 header 标签中。

{% load staticfiles %}    
    <script src="{% static "js/jquery-1.3.2.min.js" %}"></script>
    <script src="{% static "js/script.js" %}"></script>

这里我将示例 js 库放在目录位置,如 /my_app/static/js/... 所以在 src 上你需要在静态文件夹之后给出位置。希望您在按照此答案后能够显示图表。

关于javascript - django 中的 Highcharts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567209/

相关文章:

javascript - 如何在 JS 文件中使用导出的结构?

javascript - 返回 false javascript 的单选按钮仍然使用旧值调用 onchange

javascript - 对 PouchDB Promise 的结果使用 ng-repeat

python - Django ALLOWED_HOSTS 与 CORS(django-cors-headers)

javascript - Highcharts 刻度之间的空间不均匀

r - 通过 rCharts 格式化 Highcharts 图

javascript - 如何生成测试广告以检查广告的 div 宽度是否足够?

django - 您必须先安装django.contrib.messages.middleware.MessageMiddleware才能添加消息

python - 如何摆脱 SimpleDocTemplate() 中的间距。 Python。报告实验室

javascript - Highcharts - 堆积柱 - 为每个类别动态排序系列索引