json.dump not converting python list to JS array

烈酒焚心 提交于 2020-01-25 09:38:05

问题


When I attempt to pass a python list through to JavaScript in the template it doesn't parse the list into an JS array as expected but instead returns this ["Groceries", "Clothing", "Takeaways", "Alcohol"] causing the page to break.

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:


{{labels | safe}}

Solved by @Klaus D.



来源:https://stackoverflow.com/questions/52435224/json-dump-not-converting-python-list-to-js-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!