2012-03-02 26 views
7

tôi có một cái nhìn như thế này:điển trong django mẫu

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

và trong mẫu:

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

Tôi chỉ có một từ điển trong mẫu. Nhưng 4 từ điển có thể ở đây (vì info_dict) Điều gì là sai trong quan điểm?

Cảm ơn trước

Trả lời

11

Theo quan điểm của bạn, bạn chỉ tạo ra một biến (profile_dict) để giữ dicts hồ sơ.

Trong mỗi lần lặp của vòng lặp for f in profile, bạn đang tạo lại biến đó và ghi đè giá trị của từ khóa đó bằng từ điển mới. Vì vậy, khi bạn bao gồm profile_dict trong ngữ cảnh được chuyển đến mẫu, nó giữ giá trị cuối cùng được gán cho profile_dict.

Nếu bạn muốn vượt qua bốn profile_dicts cho template, bạn có thể làm điều này theo quan điểm của bạn:

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

Và sau đó trong mẫu của bạn:

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

bạn đã cứu mạng tôi. Cảm ơn – TheNone

+6

@ TheNone: crikey, sếp của bạn là * thực sự * nghiêm ngặt. Bạn được chào đón. –

Các vấn đề liên quan