2012-03-02 132 views
7

我有這樣一個觀點:字典在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: 
     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) 視圖有什麼問題?

在此先感謝

回答

11

在你看來,你只是創建了一個變量(profile_dict)持有的個人資料類型的字典。

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)) 

,然後在模板:

{% for profile_dict in profile_dicts %} 
<ul> 
    {% for k, v in profile_dict.items %} 
     <li>{{ k }} : {{ v }}</li> 
    {% endfor %} 
</ul> 
{% endfor %} 
+0

你救了我的命。謝謝 – TheNone 2012-03-02 10:39:38

+6

@TheNone:crikey,你的老闆*真的很嚴格。你非常歡迎。 – 2012-03-02 10:48:34