使用JSON将数据从Django传递到amchart JS

时间:2018-01-12 20:15:40

标签: python json django amcharts

我想将数据从我的Django视图传递到我的html,然后将数据传输到我的图表js或直接将数据传递给我的amchart。

views.py:

def nodo_detail(request,nodo_id):
El_Nodo = Nodo.objects.get(pk=nodo_id)
all_nodos = Nodo.objects.order_by('pk').all()
var = Variable()
v = dir(var)
elemento = El_Nodo.variable_set.order_by('pk').all()
watts = elemento.last().Watts
prefix = ''
chartData = "["

for t in elemento:
    chartData += prefix
    chartData += "{\n"
    chartData += "                      date: "
    chartData += '"' + str(t.Data_time.year) + "-"
    chartData += str(t.Data_time.month) + "-"
    chartData += str(t.Data_time.day) + " "
    chartData += str(t.Data_time.hour) + ":"
    chartData += str(t.Data_time.minute) + ":"
    chartData += str(t.Data_time.second) + '"' + ",\n"
    chartData += "                  value:"
    chartData += str(t.Watts) + ",\n"
    chartData += "                  volume: "
    chartData += str(t.Watts) + "\n                      }"
    prefix = ", "
chartData += "]"

context = {'El_Nodo': El_Nodo,
           'all_nodos': all_nodos,
           'v': v,
           'watts': watts,
           'chartData':chartData,
           "asdf":json.dumps(chartData)}
return render(request, 'inicio/detail.html', context)

我要传递的数据是chartData,使用for循环我尝试使用JSON格式,我也尝试使用JSON python librery。

detail.html:

{% block Stock %}
<input type="hidden"  id="stock" value="{{chartData}}"> <!-- or asdf-->
{% endblock%}

amchartjs:

var chartData = JSON.parse(document.getElementById("stock").value);
 // or directly 
var chartData = JSON.parse('{{ chartData }}');//or asdf

据我所知,通过这种方式,有必要刷新整个网页以查看新数据,还想知道如何动态地进行操作?谢谢,抱歉英文不好

1 个答案:

答案 0 :(得分:1)

进行一个返回数组的AJAX调用,然后用JavaScript填充它。这意味着要创建一个返回JSON数组的JSON视图。像这样:

class QueryResultsView(generic.TemplateView):

    template_name='your_template.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(QueryResultsView, self).get_context_data(**kwargs)
        # Create a variable you fill
        context['my_big_sql'] = MyModel.objects.filter(blabla=blibli)
        return context

从那里开始,在您的模板文件中(这是您的模板文件,而不是JavaScript文件general_study_results.html添加如下内容:

<script>
var myData = 
{% for row in my_big_sql %} 
    {{ row.column }}{% if not forloop.last %},{% endif %}
{% endfor %};
</script>

然后,由于amchartjs,您已准备好显示HTML文件中的所有数据。