Python 如何在Django模板中获取循环中键的字典值? views.py def get(self、request、*args、**kwargs): domains=Domain.objects.all() 上下文['domains']=域 域_dict={} # .......... #这里有一些域字典的代码 打印(域目录) 上下文['domain_dict']=domain_dict 返回呈现(请求、self.response_模板、上下文) 打印域\u dict

Python 如何在Django模板中获取循环中键的字典值? views.py def get(self、request、*args、**kwargs): domains=Domain.objects.all() 上下文['domains']=域 域_dict={} # .......... #这里有一些域字典的代码 打印(域目录) 上下文['domain_dict']=domain_dict 返回呈现(请求、self.response_模板、上下文) 打印域\u dict,python,html,django,templates,jinja2,Python,Html,Django,Templates,Jinja2,{4:'',3:'',1:'',5:'',7:'',2:'',6:'你是工程入学的候选人吗} 现在通过上下文将域的dict发送到模板 templates.html {%用于域中的域%} {%with domain_id=domain.id%} {{domain_dict.6}} {%endwith%} {%endfor%} 在上面的模板中,我使用{{domain\u dict.6}domain_dict.6查找键6的值。它的回报是完美的。 输出:您是否是工程入学的候选人。 但在下面

{4:'',3:'',1:'',5:'',7:'',2:'',6:'你是工程入学的候选人吗}

  • 现在通过上下文
    域的dict
    发送到
    模板
templates.html

{%用于域中的域%}
{%with domain_id=domain.id%}
{{domain_dict.6}}

{%endwith%} {%endfor%}
在上面的模板中,我使用
{{domain\u dict.6}

domain_dict.6
查找键
6
的值。它的回报是完美的。 输出:
您是否是工程入学的候选人。

  • 但在下面

{%用于域中的域%}
{%with domain_id=domain.id%}
{{domain_dict.domain_id}

{%endwith%} {%endfor%}
在上面的模板中,我使用
{{domain\u dict.domain\u id}

domain\u dict.domain\u id
查找key
domain\u id
的值。它返回null。这里
domain\u id=4,3,1,6,5,7,2
输出:
null


在这里如何返回字典键的值?我最近遇到了同样的问题。下面是解决方案的示例

喂,我们有元组

people = ('Vasya', 'Petya', 'Masha', 'Glasha')
和字典及其状态:

st = {
    'Vasya': 'married',
    'Petya': 'divorced',
    'Masha': 'married',
    'Glasha': 'unmarried'
}
我们将其作为相应视图的上下文传输到模板中:

context['people'] = people
context['st'] = st
如果我们用模板写

{% for person in people %}
    {{ person }} is {{ st.person }}
{% endfor %}
那就不行了。将显示“person”,但字典中的数据不会显示:

请注意,{{foo.bar}等模板表达式中的bar将 解释为文本字符串,不使用 变量,如果模板上下文中存在

问题的解决方案是使用另一个数据结构或在模板中使用自定义筛选器。后者的思想是向模板中的词典添加一个过滤器,它获取person的当前值并返回词典的相应值。 为此,

  • 使用应用程序在文件夹中创建新文件夹templatetags
  • 在settings.py中写入此新文件夹的路径
  • 在templatetags内部,使用名为dict_value的新过滤器创建新文件,例如filter.py:
  • 返回模板并在第一行的某个位置加载新创建的筛选器:
  • 重写模板代码,如下所示:

  • 现在它可以根据需要工作。

    解决了兄弟。。。。它的作品完美。。。
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                ...,
                os.path.join(BASE_DIR, 'your_app/templatetags'),
            ],
           ...
        }
    
    from django import template
    
    register = template.Library()
    
    @register.filter
    def dict_value(d, key):
        return d[key]
    
    {% load filter %}
    
    {% for person in people %}
        {{ person }} is {{ st|dict_value:person }}
    {% endfor %}