【问题标题】:json.dump not converting python list to JS arrayjson.dump 没有将 python 列表转换为 JS 数组
【发布时间】:2019-02-25 08:40:50
【问题描述】:

当我尝试将 python 列表传递给模板中的 JavaScript 时,它不会按预期将列表解析为 JS 数组,而是返回此 ["Groceries", "Clothing", "Takeaways", "Alcohol"] 导致页面中断。

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>

【问题讨论】:

  • {{labels | safe}} docs
  • 传奇。谢谢@K
  • 确实是传奇。检查了这些负载。这是唯一可以将简单的 Python 列表放入我的 Javascript 的方法

标签: javascript python django python-3.x django-2.0


【解决方案1】:
{{labels | safe}}

由@Klaus D 解决。

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2021-03-22
    • 2012-06-13
    • 2011-09-23
    • 2019-10-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    相关资源
    最近更新 更多