问题
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(["Groceries", "Clothing", "Takeaways", "Alcohol"]) 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