Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

How to iterate json dictionary in django template?

I am new in django and now i am trying to iterate one json dictionary in html page. I am using the {{context}} for displaying the dictionary which is passed from the view and context is the variable used to store the dictionary in render_to_response. now it is diplayed like

[
  {
    "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"
    }
  }
]

How I can iterate this dictionary to display like

username  : 1
category  : Furniture

Can anyone please help me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You shouldn't "convert it to JSON" unless you're planning to have your logic in Javascript. Instead, in your template you could iterate over the array in a for loop and traverse the dictionary to the username and category keys:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...