简体   繁体   English

我的for循环未获取值

[英]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': [{'username': '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. 我已经尝试了很多不同的for循环,但是没有一个起作用。

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. for x in mydict遍历字典仅给出键,而不是值。 So you need to do {% for item, value in mydict.items %} . 因此,您需要执行{% for item, value in mydict.items %}

Secondly, {{ result.item.username }} makes no sense at all. 其次, {{ result.item.username }}毫无意义。 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. itemresult字典中键的值,但是您不能在Django模板中进行这种间接查找。 However, luckily we have the value in the value variable. 但是,幸运的是我们在value变量中有value

Thirdly, as Kabie points out, each value is actually a single-element list. 第三,正如Kabie指出的那样,每个value实际上都是一个单元素列表。 So you'll need to access the first item in that list, and then the username member of that. 因此,您需要访问该列表中的第一项,然后访问该username成员。

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. 您正在使用print在for循环中获取输出。 This first converts the object to a string. 这首先将对象转换为字符串。 Apparently the objects in this case is some sort of xml/html objects. 显然,在这种情况下,对象是某种xml / html对象。

From inside the Django template, you don't print. 从Django模板内部,您不进行打印。 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. 您可以尝试通过str()调用将对象转换为字符串,但是总的来说,我有一种感觉,您正在尝试使模板执行某些您不应该首先将模板创建的操作。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM