json.dump不将python列表转换为JS数组 [英] json.dump not converting python list to JS array
本文介绍了json.dump不将python列表转换为JS数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试将python列表传递给模板中的JavaScript时,它没有按预期将列表解析为JS数组,而是返回此 [& Groceries&,& quot;服装",外卖"和酒精"]
导致页面中断.
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
index.html
<script type="text/javascript">
console.log(JSON.parse("{{labels}}"))
# => converts this to console.log(["Groceries", "Clothing", "Takeaways", "Alcohol"]) in JS and breaks.
</script>
推荐答案
{{labels | safe}}
由@Klaus D解决.
Solved by @Klaus D.
这篇关于json.dump不将python列表转换为JS数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文