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

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

当我尝试将 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/

相关文章:

javascript - 使用 create-react-app 创建应用程序时出现 React 和 Bootstrap4 问题

javascript - React组件如何简化这个onClick功能?

javascript - Sencha touch 2 native 版本未加载

javascript - 删除类 onclick ... angular js

python - 使用类别和子类别优化 Django 中的数据库查询

python - 如何在python中的字典中搜索值

javascript - Django 翻译 - 翻译星期几

python - 在没有多次数据库请求的情况下在 Django 中多次调用外键对象

python - 将 np.savetxt 和 np.loadtxt 与多维数组一起使用

django - 无法使 nginx 内部重定向工作