Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary in django template

Tags:

django

I have a view like this:

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

and in template:

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

I have only one dictionary in template. But 4 dictionary might be here (because info_dict) What is wrong in view?

Thanks in advance

like image 819
TheNone Avatar asked Mar 02 '12 10:03

TheNone


1 Answers

In your view, you’ve only created one variable (profile_dict) to hold the profile dicts.

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.

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

And then in your template:

{% for profile_dict in profile_dicts %}
<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>
{% endfor %}
like image 129
Paul D. Waite Avatar answered Sep 27 '22 21:09

Paul D. Waite