Django项目中HTML模板无法显示数据库对象数据问题求助
Django数据库对象无法在HTML页面展示问题修复
问题根因
代码存在变量名拼写错误:视图层向模板传递的上下文变量名为outform,但HTML模板中所有调用该变量的位置都错写为outfrom(字母f、r顺序颠倒),模板无法匹配到对应变量,因此无法渲染数据。
补充说明:Django模板默认对不存在的变量做静默处理,不会主动抛出异常,这也是后台能正常打印出查询结果、但页面不显示数据的原因。
修复方案
将模板中所有错误的outfrom变量名统一修改为和视图上下文一致的outform即可,修正后的模板代码如下:
{% if outform %} <p>Out Form Exist</p> {% else %} <p>Not Exist</p> {% endif %} <div class="mt-2" id="out-template"> <label for="template-out" class="form-label">Select Output Template</label> <select class="form-select" aria-label="Default out select example" name="out_template_id" id="template-out"> <option value="0" selected></option> {% for out in outform %} <option value="{{ out.id }}">{{ out.title }}</option> {% endfor %} </select> </div>
开发调试小技巧
为了快速定位这类变量拼写问题,开发阶段可以在项目settings.py的模板配置中添加string_if_invalid配置,让不存在的变量直接显示提示文本,避免静默失败:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], # 新增以下配置,生产环境部署前记得删除 'string_if_invalid': '⚠️ 不存在的变量:%s', }, }, ]
内容的提问来源于stack exchange,提问作者Thomas Brush
相关产品推荐
相关产品推荐

