Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript json.dump未将python列表转换为JS数组_Javascript_Python_Django_Python 3.x_Django 2.0 - Fatal编程技术网

Javascript json.dump未将python列表转换为JS数组

Javascript json.dump未将python列表转换为JS数组,javascript,python,django,python-3.x,django-2.0,Javascript,Python,Django,Python 3.x,Django 2.0,当我试图将python列表传递给模板中的JavaScript时,它不会像预期的那样将列表解析为JS数组,而是返回这个[“杂货”、“衣服”、“外卖”、“酒精”],导致页面中断 view.py def labels(): category_labels = [] for item in Purchase.objects.order_by().values_list('type', flat=True).distinct(): category_labels.appen

当我试图将python列表传递给模板中的JavaScript时,它不会像预期的那样将列表解析为JS数组,而是返回这个
[“杂货”、“衣服”、“外卖”、“酒精”]
,导致页面中断

view.py

def labels():
    category_labels = []
    for item in Purchase.objects.order_by().values_list('type', flat=True).distinct():
        category_labels.append(item)

    return category_labels


def index(request):
    try:
        purchases = Purchase.objects.all().order_by('-time')
        total_spending = round(Purchase.objects.aggregate(Sum('amount'))['amount__sum'], 2)
    except Purchase.DoesNotExist:
        raise Http404("Could not find any purchases.")

    context = {
        'purchases': purchases,
        'total_spending': total_spending,
        'spending_by_category': prepare_total_spending(),
        'total_spending_all_categories': total_spending_all_categories(),
        'labels': json.dumps(labels()),
    }

    return render(request, 'main/index.html', context)
index.html

<script type="text/javascript">
    console.log(JSON.parse("{{labels}}"))
     # => converts this to console.log([&quot;Groceries&quot;, &quot;Clothing&quot;, &quot;Takeaways&quot;, &quot;Alcohol&quot;]) in JS and breaks.
</script>

log(JSON.parse(“{{labels}}”))
#=>将其转换为JS和Break中的console.log([“杂货”、“衣服”、“外卖”、“酒精”)。

由@Klaus D.

{{labels | safe}}}
图例解决。真的谢谢你@KLegend。检查了这些货物的装载量。这是将简单的Python列表放入Javascript的唯一方法
{{labels | safe}}