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

Django项目中无法从字典取值的问题求助

Django模板字典动态取值问题解决办法

你遇到的问题核心是:Django模板的点语法.在操作字典时,只会查找字符串字面量的键,不会解析变量。

比如你写的{{ duties.index }},模板会去字典里找键为"index"的元素,而不是变量index的值;{{ duties.person.duty_type }}同理,是找键为"person.duty_type"的字符串键,自然取不到对应的值。

下面给你几种可行的解决方法:

方法1:自定义模板过滤器(推荐)

这是最灵活的方案,适合所有动态取值场景:

  1. 在你的Django应用目录下创建templatetags文件夹,里面新建两个文件:__init__.py(空文件即可)和custom_filters.py
  2. 在custom_filters.py中写入以下代码:
from django import template

register = template.Library()

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)
  1. 在需要使用的模板顶部加载这个过滤器:
{% load custom_filters %}
  1. 之后直接用过滤器取值,两种写法都可以:
{% with index=person.duty_type %}
    <div class="small text-gray-500">{{ duties|get_item:index }}</div>
{% endwith %}

或者直接省略with标签:

<div class="small text-gray-500">{{ duties|get_item:person.duty_type }}</div>

方法2:循环字典键值对匹配

如果不想自定义过滤器,可以把字典转成键值对列表传到模板:

  • 在视图函数中,把duties转换成列表:
duties_list = list(duties.items())
# 然后把duties_list传到模板上下文
  • 模板中循环匹配:
{% for key, value in duties_list %}
    {% if key == person.duty_type %}
        <div class="small text-gray-500">{{ value }}</div>
    {% endif %}
{% endfor %}

方法3:硬编码判断(适合值少的场景)

如果duty_type的可选值不多,也可以直接用条件判断:

<div class="small text-gray-500">
    {% if person.duty_type == 1 %}Crew
    {% elif person.duty_type == 2 %}Cast
    {% elif person.duty_type == 3 %}Director
    {% elif person.duty_type == 4 %}Writers
    {% endif %}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:00:03