Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong here? Iterating over a dictionary in Django template

I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value.

Here's what I have in models.py:

class Manors(models.Model):
    structidx = models.IntegerField(primary_key=True, verbose_name="ID")    
    county = models.CharField(max_length=5, null=True, blank=True, verbose_name="County")   

    def get_fields(self):
            d = {}
            #d["database"] = "pubs"
            #d["uid"] = "sa"
            for field in Manors._meta.fields:
                d[field.verbose_name(self)] = field.value_to_string(self)
            return d

And in views.py:

    manor_stats = Manors.objects.get(structidx__exact=id)
    return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))

And in the template:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields %}
 <li> {{ key }}: {{ value }} </li>
{% endfor %}
</ul>

But I just get a weird, distorted-looking list like:

u: i
d: a

It doesn't even work if I use hard-coded values in models.py (as shown commented out above).

What's wrong here? Been trying to work this out for hours:(

---------- UPDATED ---------------

Trying with

def get_fields(self):
        d = {}
        for field in Manors._meta.fields:
            d[field.verbose_name(self)] = { "verbose": field.verbose_name(self), "value": field.value_to_string(self) }
        return d

and in template:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields %}
 <li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>

just produces a blank list....

like image 281
AP257 Avatar asked Feb 07 '10 21:02

AP257


People also ask

How do you loop a dictionary in a Django template?

To iterate through dictionary in a dictionary in a Python Django template, we can loop through the items with a for loop. to loop through the data dict's entries with a for loop. We get the key value pairs with data.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


2 Answers

To iterate a dictionary wouldn't you need:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields.items %}
 <li> {{ key }}: {{ value }}</li>
 {% endfor %}
</ul>

But I'd suggest retrieving the dictionary from the function first:

Views.py:

    manor_stats = Manors.objects.get(structidx__exact=id).get_fields()
    return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))

And then:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.items %}
 <li> {{ key }}: {{ value }}</li>
 {% endfor %}
</ul>

But only because I'm not that familiar with how much dereferencing the templating system can do. Seeing as you know how to deference it you're saving the effort of having the renderer work it out.

like image 76
MattH Avatar answered Sep 23 '22 02:09

MattH


Iterating over a dict yields its keys. I don't know why Django thinks you want to do an incomplete sequence expansion on the key name instead of throwing an exception, but I'll chalk it up to ANOTHER one of Django's template engine's quirks.

Anyways, yes, get key from the dict in your for loop, then use key and dict.key inside it.

like image 39
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 02:09

Ignacio Vazquez-Abrams