Django模板中的字典 [英] Dictionary in django template
问题描述
我有这样的看法:
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>
模板中只有一本字典。但是这里可能有4个字典(因为info_dict)
看来有什么问题?
I have only one dictionary in template. But 4 dictionary might be here (because info_dict) What is wrong in view?
预先感谢
推荐答案
在您看来,您仅创建了一个变量( profile_dict
)来保存配置文件字典。
In your view, you’ve only created one variable (profile_dict
) to hold the profile dicts.
在配置文件中的 for f
循环的每次迭代中,您都在重新创建该变量,并用a覆盖其值。新字典。因此,当您在传递给模板的上下文中包含 profile_dict
时,它将保存分配给 profile_dict
的最后一个值。
In each iteration of your for f in profile
loop, you’re re-creating that variable, and overwriting its value with a new dictionary. So when you include profile_dict
in the context passed to the template, it holds the last value assigned to profile_dict
.
如果要将四个profile_dicts传递给模板,则可以在您的视图中执行以下操作:
If you want to pass four profile_dicts to the template, you could do this in your view:
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))
然后在您的模板中:
{% for profile_dict in profile_dicts %}
<ul>
{% for k, v in profile_dict.items %}
<li>{{ k }} : {{ v }}</li>
{% endfor %}
</ul>
{% endfor %}
这篇关于Django模板中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!