You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目中如何将Python变量传入JavaScript?

在Django中传递Python数值到Google Charts的规范实现

这是在Django项目里把后端Python函数的数值安全传递给前端Google Charts的标准做法,分两步就能搞定:

1. 后端视图准备数据

首先在对应的视图函数里,调用你的数值生成函数,把结果放到上下文里传给模板:

from django.shortcuts import render

def chart_view(request):
    # 替换成你的实际数值生成函数
    lol_hours = your_numeric_function_1()
    eat_hours = your_numeric_function_2()

    # 把数据打包进上下文,传给模板
    context = {
        'lol_hours': lol_hours,
        'eat_hours': eat_hours,
    }
    return render(request, 'your_template_path.html', context)

2. 前端模板安全传递数据到JS

Django提供了json_script模板标签(Django 2.1及以上支持),这是最安全规范的方式,能避免XSS风险,同时完美处理Python到JS的数据转换。

修改你的模板代码如下:

{% extends "gappi_tmp/wrapper.html" %} 

{% block content %} 
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <!-- 先将后端数据渲染为安全的JSON脚本标签 -->
    {{ lol_hours|json_script:"lol-hours" }}
    {{ eat_hours|json_script:"eat-hours" }}

    <div style="padding-top: 5px; background: cornflowerblue; width: auto; height: 300px;" id="piechart"></div>

    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            // 从JSON标签中读取后端传递的数值
            const lolHours = JSON.parse(document.getElementById('lol-hours').textContent);
            const eatHours = JSON.parse(document.getElementById('eat-hours').textContent);

            var data = google.visualization.arrayToDataTable([
                ['Task', 'Hours per Day'],
                ['lol', lolHours], // 替换成后端传递的变量
                ['Eat', eatHours]  // 替换成后端传递的变量
            ]);

            var options = {
                title: 'Inbox | Outbox'
            };

            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            chart.draw(data, options);
        }
    </script>
</body> 
{% endblock %}

兼容旧版Django的方案

如果你的Django版本低于2.1,可以在视图里手动用json.dumps处理数据,再传到模板:

import json
from django.shortcuts import render

def chart_view(request):
    lol_hours = your_numeric_function_1()
    eat_hours = your_numeric_function_2()

    context = {
        'lol_hours_json': json.dumps(lol_hours),
        'eat_hours_json': json.dumps(eat_hours),
    }
    return render(request, 'your_template_path.html', context)

然后模板里直接在JS中使用:

// 读取后端传递的JSON数据
const lolHours = {{ lol_hours_json|safe }};
const eatHours = {{ eat_hours_json|safe }};

为什么推荐json_script?它会自动将Python数据转换成合法的JSON格式,并且包裹在type="application/json"的script标签里,既不会被浏览器当作JS执行,又能被JS安全读取,彻底避免了直接渲染变量可能带来的XSS风险,是Django官方推荐的前后端数据传递方式。

内容的提问来源于stack exchange,提问作者user8163099

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:20:03