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

如何修复JavaScript模板字面量中for循环不生效,渲染Django查询集为Bootstrap表格下拉框问题

问题修正方案

你当前的代码存在3个核心错误:

  • 后端传递的Django QuerySet直接通过{{ Publisher }}渲染到JS中是纯字符串,无法直接遍历
  • 模板字面量仅支持嵌入表达式,不支持直接写入for循环这类语句,需要提前生成循环后的HTML片段再拼接
  • 原有option的value和显示值写死,没有取publisher的实际数据,选中判断逻辑也错误

步骤1:调整后端数据传递逻辑

修改view.py,将QuerySet序列化为纯列表方便前端解析:

def view_material(request):
    # 只取publisher的名称字段转为普通列表,也可根据需求保留id等字段
    query_results_publisher = list(Publisher.objects.values_list('name', flat=True))
    return render(request, 'material/index.html', context={'Publisher':query_results_publisher})

步骤2:修正前端模板与JS逻辑

修改index.html的相关代码,首先安全注入publisher数组,再重写renderPublisher函数:

...
<th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>
...
<!-- 用Django的json_script过滤器安全注入JSON数据,避免XSS风险 -->
{{ Publisher|json_script:"publisher-data" }}

<script>
    // 从注入的script标签中读取publisher数组
    const Publisher = JSON.parse(document.getElementById('publisher-data').textContent);
    
    function renderPublisher(value) {
        // 先生成所有option的HTML片段
        let optionHtml = '';
        for (const pub of Publisher) {
            // 遍历判断当前publisher是否匹配传入的value,选中对应项
            const selected = value === pub ? 'selected' : '';
            optionHtml += `<option value="${pub}" ${selected}>${pub}</option>`;
        }
        // 把生成的option片段拼入select的模板字符串中
        return `
            <select style="width: 7em" name="" id="">
                ${optionHtml}
            </select>
        `;
    }
</script>

额外说明

如果需要保留publisher的id作为option的value,只需要把后端查询改为values('id', 'name'),前端遍历的时候取pub.id和pub.name即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:36:01