2012-03-02 20 views
7

Mam widoku tak:słownik w Django szablonu

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

oraz w Szablon:

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

mam tylko jeden słownik w szablonie. Ale 4 słownik może być tutaj (ponieważ info_dict) Co jest nie tak w widoku?

góry dzięki

Odpowiedz

11

Państwa zdaniem utworzeniu jednej zmiennej (profile_dict) tylko do przechowywania dicts profil.

W każdej iteracji pętli for f in profile ponownie tworzysz tę zmienną i nadpisujesz jej wartość nowym słownikiem. Jeśli więc uwzględnisz profile_dict w kontekście przekazanym do szablonu, to zawiera ona ostatnią wartość przypisaną do profile_dict.

Jeśli chcesz przekazać cztery profile_dicts do szablonu, można zrobić to w widoku:

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

a następnie w szablonie:

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

zapisaniu moje życie. Dzięki – TheNone

+6

@Nie: crikey, twój szef jest * naprawdę * ścisły. Nie ma za co. –

Powiązane problemy