如何在django模板中迭代json字典?

时间:2012-03-06 21:34:56

标签: django json dictionary

我是django的新手,现在我想在html页面中迭代一个json字典。我使用{{context}}来显示从视图传递的字典,context是用于在render_to_response中存储字典的变量。现在它像是

[
  {
    "pk": 5, 
    "model": "Auction.newauction", 
    "fields": {
      "username": 1, 
      "category": "furniture", 
      "description": "Made of Wood", 
      "end_date": "2012-05-01 11:00:00", 
      "start_price": "100", 
      "title": "Table", 
      "start_date": "2012-03-04 11:24:11"
    }
  }
]

如何迭代此词典以显示

username  : 1
category  : Furniture

任何人都可以帮助我

1 个答案:

答案 0 :(得分:2)

除非您计划在Javascript中使用逻辑,否则不应“将其转换为JSON”。相反,在您的模板中,您可以在for循环中遍历数组并将字典遍历到用户名和类别键:

{% for c in context %}
  <div>username: {{ c.fields.username }}</div>
  <div>category: {{ c.fields.category }}</div>
{% endfor %}