简体   繁体   English

从Django到Javascript的Python数据

[英]Python data from Django to Javascript

I am busy on a Django app which analyzes a variety of data (largely using pandas) and then displays the results using Google charts. 我正忙于Django应用程序,该应用程序分析各种数据(主要使用熊猫),然后使用Google图表显示结果。

Im having trouble figuring out the best way to pass my data from the django view.py which will generally be in a Pandas dataframe or a dict, through to be used in the template files (which use javascript for the google charts). 我在找出最好的方式从django view.py中传递我的数据时遇到麻烦,该视图通常在Pandas数据框或dict中通过,以便在模板文件中使用(使用javascript用于google图表)。

Here's some code showing a javascript function for displaying one of the charts. 这是一些代码,显示了用于显示图表之一的javascript函数。 In this example i've hard coded the data into the chart (ie: The years and the sales have been manually typed in). 在此示例中,我已将数据硬编码到图表中(即:年和销售额已手动输入)。 However what needs to be done is to instead use the data from the pandas dataframe. 但是,需要做的是改为使用熊猫数据框中的数据。

function drawChart() {

    var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales'],
        ['2004',  1000],
        ['2005',  1170],
        ['2006',  660],
        ['2007',  1030]
    ]);

    var options = {
        title: 'Company Performance',
        hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    chart.draw(data, options);
    }

It's easy enough to pass through single variables or even lists using the django template language {{ var }}. 使用Django模板语言{{var}}可以很容易地传递单个变量甚至列表。 However im not entirely sure how to pass through more complicated dataframes, dicts, etc to be used in javascript functions. 但是,我不能完全确定如何在JavaScript函数中使用更复杂的数据帧,字典等。

Many thanks. 非常感谢。

Is this what you want? 这是你想要的吗?

views.py: views.py:

import json

def some_view_func(request):
    data = [
        ['Year', 'Sales'],
        ['2004',  1000],
        ['2005',  1170],
        ['2006',  660],
        ['2007',  1030]
    ]
    render(request, 'template.html', {'data': json.dumps(data)})

template.html : template.html

<script>
    var data = google.visualization.arrayToDataTable(JSON.parse({{data}}));
</script>

this is the way to achieve what I think you want 这是实现我认为想要的方式

def view_func(request):
    data =pd.DataFrame(np.random.randn(20, 5)) 

    render(request, 'template.html', {'data': data.to_html()})

See the documentation for extra details on CSS styling and other things. 有关CSS样式和其他内容的更多详细信息,请参见文档

Also implement data as 'safe' in your template as follows: 还可以在模板中将数据实现为“安全”,如下所示:

{{ data | safe }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM