如何从django simple_tag返回JSON?

时间:2018-07-12 06:01:36

标签: python json django amcharts

我是Django的新手,在这里我将amchart与我的应用程序集成在一起。我创建了一个simple_tag方法来为dataProvider设置一个值。

这是我的amchart代码,

var chart = AmCharts.makeChart("chartdiv-{{ server.id }}", {
                  "theme": "chalk",
                  "type": "serial",
                  "dataProvider": '{% get_space_occupation server.SpaceOccupied %}',
                  "valueAxes": [{
                      "stackType": "3d",
                      "unit": "GB",
                      "position": "left",
                      "title": "Memory space rate",
                  }]

当我尝试返回哈希数组时,它没有按预期返回JSON。这是我在自定义模板标签中的代码,

from django import template
from django.http import JsonResponse
from django.core import serializers

@register.simple_tag
def get_space_occupation(space_occupied):
    data = [{
        "Drive": "C",
        "FreeSpace": 131,
        "Total": 250
    }]
    # datas_serialized = serializers.serialize('json', data)
    return JsonResponse(data, safe=False)

这就是我在模板中得到的,

var chart = AmCharts.makeChart("chartdiv-1", {
                  "theme": "chalk",
                  "type": "serial",
                  "dataProvider": '<JsonResponse status_code=200, "application/json">',
                  "valueAxes": [{
                      "stackType": "3d",
                      "unit": "GB",
                      "position": "left",
                      "title": "Memory space rate",
                  }]

请帮助我解决此问题,如果我错了,请纠正我。

1 个答案:

答案 0 :(得分:0)

从您的请求发送json数据。并接收脚本。

@register.simple_tag
def get_space_occupation(space_occupied):
    data = [{
        "Drive": "C",
        "FreeSpace": 131,
        "Total": 250
    }]
    return json.dumps(data)

在脚本中,您几乎没有选择。

首先,尝试autoescape

{% autoescape off %}
var dateProvider = '{% get_space_occupation server.SpaceOccupied %}'
{% autoescape %}
var chart = AmCharts.makeChart("chartdiv-{{ server.id }}", {
              "theme": "chalk",
              "type": "serial",
              "dataProvider": dataProvider,
              "valueAxes": [{
                  "stackType": "3d",
                  "unit": "GB",
                  "position": "left",
                  "title": "Memory space rate",
              }]

如果它不起作用,请使用JSON.parse作为数据。

像这样

var dateProvider = JSON.parse('{% get_space_occupation server.SpaceOccupied %}');