我有这样的观点:
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))
Run Code Online (Sandbox Code Playgroud)
并在模板中:
<ul>
{% for k, v in profile_dict.items %}
<li>{{ k }} : {{ v }}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
模板中只有一个字典.但是4个字典可能在这里(因为info_dict)在视图中出了什么问题?
提前致谢
Pau*_*ite 12
在您的视图中,您只创建了一个变量(profile_dict)来保存配置文件dicts.
在循环的每次迭代中for f in profile,您将重新创建该变量,并使用新字典覆盖其值.因此,当您profile_dict在传递给模板的上下文中包含它时,它将保留分配给的最后一个值profile_dict.
如果要将四个profile_dicts传递给模板,可以在视图中执行以下操作:
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))
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中:
{% for profile_dict in profile_dicts %}
<ul>
{% for k, v in profile_dict.items %}
<li>{{ k }} : {{ v }}</li>
{% endfor %}
</ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6622 次 |
| 最近记录: |