开发者

My for loop doesn't get the values

Here's what I have:

result = defaultdict(<type 'list'>,
{'USA': [{'username': 'user123', 'first-name': 'John', 'last-name': 'Doe'}],
 'Europe': [{'userna开发者_C百科me': 'myname654', 'first-name': 'Peter', 'last-name': 'Johnson'}]
})

Here's the output I want to get

<html>
  <body>
    <h1> USA </h1>
    <p> user123, John Doe</p>

    <h1> Europe </h1>
    <p> myname654, Peter Johnson</p> 
  </body>
</html>

I've tried tons of different for loops, but none of them worked.

Here's what I have, but it doesn't work.

{% for item in result %}
<h1> {{ item }} </h1>
<p> {{ result.item.username }} </p>
{% endfor %}


Result is a dictionary. Iterating through a dictionary with for x in mydict just gives the keys, not the values. So you need to do {% for item, value in mydict.items %}.

Secondly, {{ result.item.username }} makes no sense at all. item is a the value of a key into the result dict, but you can't do that sort of indirect lookups in Django templates. However, luckily we have the value in the value variable.

Thirdly, as Kabie points out, each value is actually a single-element list. So you'll need to access the first item in that list, and then the username member of that.

Putting it all together:

{% for item, value in result.items %}
<h1> {{ item }} </h1>
<p> {{ value.0.username }} </p>
{% endfor %}


You are using print to get output in your for loop. This first converts the object to a string. Apparently the objects in this case is some sort of xml/html objects.

From inside the Django template, you don't print. You could try converting the objects to string via a str() call, but in general I have the feeling you are trying to make the templates do something that you shouldn't make templates to in the first place.

Try having a method on the model object that returns the string you want, and inserting that into the template instead.


I think the line:

<p> {{ result.item.username }} </p>

should be:

<p> {{ result.item.0.username }} </p>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜