json.dump not converting python list to JS array

280 Views Asked by At

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

There are 1 best solutions below

0
On
{{labels | safe}}

Solved by @Klaus D.