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

Django视图关联变量取值异常:模板无法显示机构名称

问题分析与解决

你的代码有两个关键问题导致无法显示机构名称:

1. 视图里的赋值逻辑完全错误

在try块里,你明明拿到了正确的institute_name,但却错误地把form2[institute_code]赋值成了"N/A"——不管有没有找到匹配的机构,最终form2里全是"N/A",自然无法显示正确名称。

2. 模板里访问字典的方式不对

模板循环的是form1,每个循环项是i,你需要用i.Centre_code作为键去取form2里的对应值,而不是用form2.item.institute_code(item根本不是模板里的有效变量)。


修复方案一:修正字典赋值与模板访问

修改后的视图代码:

def view_eligibility_admin(request):
    form1 = Eligibility_Check.objects.all() 
    form2 = {}  # 存储机构名称的字典
    for item in form1:
        institute_code = item.Centre_code
        try:
            register_entry = Register.objects.get(institute_code=institute_code) 
            # 把找到的机构名称存入字典,而非错误的"N/A"
            form2[institute_code] = register_entry.institute_name
        except Register.DoesNotExist:
            # 仅当找不到匹配项时设为"N/A"
            form2[institute_code] = "N/A"
    context = {'form1': form1, 'form2': form2}
    return render(request, 'view_eligibiity_admin.html', context)

修改后的模板循环代码:

{% for i in form1 %}
<tr>
    <td>{{ forloop.counter }}</td>
    <td>{{ i.Centre_code }} / {{ i.Serial_number }}</td>
    <td>{{ i.Date_of_survey }}</td>
    <td>{{ i.District }}</td>
    <td>{{ i.Voter_id }}</td>
    <td>{{ i.Ec }}</td>
    <!-- 用当前循环项的Centre_code作为键访问form2字典 -->
    <td>{{ form2[i.Centre_code] }}</td>               
    <td class="text-center">
        <a class="btn btn-primary" href="{% url 'view_eligibility_pid' i.pk %}"><i class="fa fa-eye" aria-hidden="true"></i> </a> 
    </td>
</tr>
{% endfor %}

修复方案二:直接给查询集对象附加属性(更简洁)

这种方式不用额外维护字典,直接给每个Eligibility_Check对象加一个institute_name属性,模板里直接调用即可:

修改后的视图代码:

def view_eligibility_admin(request):
    form1 = Eligibility_Check.objects.all() 
    for item in form1:
        try:
            register_entry = Register.objects.get(institute_code=item.Centre_code) 
            item.institute_name = register_entry.institute_name
        except Register.DoesNotExist:
            item.institute_name = "N/A"
    context = {'form1': form1}
    return render(request, 'view_eligibiity_admin.html', context)

修改后的模板对应列代码:

<td>{{ i.institute_name }}</td>

这种写法更直观,也减少了模板里的复杂度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:17:34