django模板中的字典

django模板中的字典,django,Django,我有这样的看法: info_dict = [{u'Question 1': ['13365', '13344']}, {u'Question 2': ['13365']}, {u'Question 3': []}] for key in info_dict: for k, v in key.items(): profile = User.objects.filter(id__in=v, is_active=True) for f in profile:

我有这样的看法:

info_dict =  [{u'Question 1': ['13365', '13344']}, {u'Question 2': ['13365']}, {u'Question 3': []}]

for key in info_dict:
    for k, v in key.items():
        profile = User.objects.filter(id__in=v, is_active=True)
    for f in profile:
        wanted_fields = ['job', 'education', 'country', 'city','district','area']
        profile_dict = {}
        for w in wanted_fields:
            profile_dict[f._meta.get_field(w).verbose_name] = getattr(f, w).name

return render_to_response('survey.html',{
    'profile_dict':profile_dict,
},context_instance=RequestContext(request))
在模板中:

<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>
{% for profile_dict in profile_dicts %}
<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>
{% endfor %}
    {profile_dict.items%中k,v的百分比}
  • {{k}}:{{v}
  • {%endfor%}
我的模板里只有一本字典。但是4字典可能在这里(因为信息) 你认为哪里不对


提前感谢

在您看来,您只创建了一个变量(
profile\u dict
)来保存配置文件dict

在profile循环中的f的
每次迭代中,您都在创建该变量,并用新字典覆盖其值。因此,当您在传递给模板的上下文中包含
profile\u dict
时,它会保存分配给
profile\u dict
的最后一个值

如果要将四个概要文件传递给模板,可以在视图中执行此操作:

info_dict =  [{u'Question 1': ['13365', '13344']}, {u'Question 2': ['13365']}, {u'Question 3': []}]

# Create a list to hold the profile dicts
profile_dicts = []

for key in info_dict:
    for k, v in key.items():
        profile = User.objects.filter(id__in=v, is_active=True)
    for f in profile:
        wanted_fields = ['job', 'education', 'country', 'city','district','area']
        profile_dict = {}
        for w in wanted_fields:
            profile_dict[f._meta.get_field(w).verbose_name] = getattr(f, w).name

        # Add each profile dict to the list
        profile_dicts.append(profile_dict)

# Pass the list of profile dicts to the template
return render_to_response('survey.html',{
    'profile_dicts':profile_dicts,
},context_instance=RequestContext(request))
然后在模板中:

<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>
{% for profile_dict in profile_dicts %}
<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>
{% endfor %}
{profile_dicts%中profile_dicts的%
    {profile_dict.items%中k,v的百分比}
  • {{k}}:{{v}
  • {%endfor%}
{%endfor%}
你救了我的命。Thanks@TheNone:哎呀,你的老板真的很严厉。不客气。