0

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>
3
  • 2
    {{labels | safe}} docs Commented Sep 21, 2018 at 1:08
  • Legend. Thank you @K Commented Sep 21, 2018 at 1:14
  • Legend indeed. Checked loads of these. This is the only thing that worked to get a simple Python list into my Javascript Commented Nov 10, 2019 at 10:12

1 Answer 1

1
{{labels | safe}}

Solved by @Klaus D.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.