如何在 Django 模板中获取循环内键的字典值?

How to get dictionary value of a key inside a loop in Django Template?

views.py

def get(self, request, *args, **kwargs):
    domains = Domain.objects.all()
    context['domains'] = domains

    domain_dict = {}
    # ..........
    # ..........some codes here for domain_dict dictionary
    print(domain_dict)
    context['domain_dict'] = domain_dict
    return render(request, self.response_template, context)

{4: '', 3: '', 1: '', 5: '', 7: '', 2: '', 6: 'Are you a candidate for the engineering admission '}

templates.html

<div class="col-md-8">
    <div class="tab-content">
        {% for domain in domains %}
            {% with domain_id=domain.id %} 
            <div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
                <div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
                </div>  
                <h3><a href="#">Name: {{domain.name}} ID: {{domain_id}}</a></h3>
                <p>{{domain_dict.6}}</p>
            </div>
            {% endwith %}
        {% endfor %}
    </div>
</div>

In the above template I use <p>{{domain_dict.6}}</p>. domain_dict.6 to find the value of key 6. It returns perfectly. Outputs: Are you a candidate for the engineering admission.

<div class="col-md-8">
    <div class="tab-content">
        {% for domain in domains %}
            {% with domain_id=domain.id %} 
            <div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
                <div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
                </div>  
                <h3><a href="#">Name: {{domain.name}} ID: {{domain_id}}</a></h3>
                <p>{{domain_dict.domain_id}}</p>
            </div>
            {% endwith %}
        {% endfor %}
    </div>
</div>

In the above template I use <p>{{domain_dict.domain_id}}</p>. domain_dict.domain_id to find the value of key domain_id. It returns null. Here domain_id = 4,3,1,6,5,7,2 Outputs: null

如何return这里的字典的一个键的值?

我最近 运行 遇到了同样的问题。这是解决方案的示例。

说,我们有元组

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' 会被显示,但字典中的数据不会。 Because :

Note that bar in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable bar, if one exists in the template context.

问题的解决方案要么使用其他数据结构,要么在模板中使用自定义过滤器。后者的想法是在模板中为您的字典添加一个过滤器,它采用 person 的当前值和字典的对应值 returns 。 为此,

  1. 在包含您的应用程序的文件夹中创建新文件夹 templatetags,
  2. settings.py,
  3. 中写入这个新文件夹的路径
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            ...,
            os.path.join(BASE_DIR, 'your_app/templatetags'),
        ],
       ...
    }
  1. templatetags 中创建新文件,例如 filter.py 使用我们的新过滤器 dict_value:
from django import template

register = template.Library()

@register.filter
def dict_value(d, key):
    return d[key]
  1. 返回您的模板并在第一行某处加载新创建的过滤器:
{% load filter %}
  1. 像这样重写模板代码:
{% for person in people %}
    {{ person }} is {{ st|dict_value:person }}
{% endfor %}

现在可以按需工作了。