You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django的{% block js %}块中遍历视图传递的queryset?

在Django模板的{% block js %}中访问视图传递的数据

完全可行,Django模板的任何代码块(包括{% block js %})都能正常访问视图通过上下文传递的变量——不管是普通数组、QuerySet还是单个数值。

示例代码

视图部分(传递数据)

# views.py
from django.shortcuts import render
from .models import Product

def product_list(request):
    # 从模型获取QuerySet
    products = Product.objects.all()
    # 单个数值
    price_threshold = 100
    # 普通数组
    tags = ['热销', '新品', '折扣']
    # 将数据传入模板上下文
    return render(request, 'product_list.html', {
        'products': products,
        'price_threshold': price_threshold,
        'tags': tags
    })

模板的{% block js %}部分(使用数据)

<!-- product_list.html -->
{% block js %}
<script>
// 直接访问单个数值
const priceThreshold = {{ price_threshold }};
console.log('价格阈值:', priceThreshold);

// 遍历普通数组生成JS数组
const tags = [{% for tag in tags %}'{{ tag }}'{% if not forloop.last %}, {% endif %}];
console.log('标签列表:', tags);

// 遍历QuerySet,生成JS对象数组
const products = [
    {% for product in products %}
    {
        name: '{{ product.name|escapejs }}',
        price: {{ product.price }}
    }{% if not forloop.last %}, {% endif %}
    {% endfor %}
];
console.log('产品列表:', products);
</script>
{% endblock %}

注意事项

  • 处理字符串类型的变量时,务必添加|escapejs过滤器,避免字符串中的引号、换行符等导致JS语法错误
  • 生成JS数组/对象时,用{% if not forloop.last %}控制逗号,防止最后一个元素后多出逗号引发语法问题
  • 如果QuerySet数据量极大,建议改用AJAX异步获取数据,避免页面加载时生成过于庞大的JS代码,影响页面性能

内容的提问来源于stack exchange,提问作者Sanket Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:20:28