gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:05:20 30 4
gpt4 key购买 nike

当我尝试将 python 列表传递给模板中的 JavaScript 时,它不会按预期将该列表解析为 JS 数组,而是返回此 ["Groceries", "Clothing", ""外卖”、“酒精”]导致页面损坏。

查看.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>

最佳答案

{{labels | safe}}

由@Klaus D 解决。

关于javascript - json.dump 未将 python 列表转换为 JS 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435224/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com