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

时间:2018-09-21 01:01:52

标签: javascript python django python-3.x django-2.0

当我尝试将python列表传递给模板中的JavaScript时,它没有按预期将列表解析为JS数组,而是返回了此["Groceries", "Clothing", "Takeaways", "Alcohol"]导致页面中断。

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>

1 个答案:

答案 0 :(得分:0)

{{labels | safe}}

由@Klaus D解决。