简体   繁体   中英

How to iterate over a python dictionary in django template

I saw a variety of answers and I can't figure out what I am doing wrong currently. I am using python 2.7 and django 1.5.1. Below is the code for my template:

  {% for key, value in chartdata.items %}
    key = {{ key }};
    value = {{ value }};
    console.log( key + ":" +  value  );
    alert('here');
  {% endfor %}

And in view.py I am sending the dictionary as:

  chartdata= getChartData(request.session['userphone'])
    log.debug(chartdata)
    table=getUserInfo(request.session['userphone'],str(request.user))
    return render(request,'users.html',{'table':table,'topics':request.session['topics'],'profilepic':request.session['profilepic'],'chartdata':chartdata,'time':str(time.time())})

The log.debug(chartdata) is returning the following result in my logfile:

  [11/Jul/2013 16:49:12] DEBUG [karnadash.views:179] [(85, '2013-07-08'), (120, '2013-07-08'), (205, '2013-07-08'), (305, '2013-07-08'), (405, '2013-07-08'), (505, '2013-07-08'), (547, '2013-07-09'), (564, '2013-07-09'), (581, '2013-07-09'), (607, '2013-07-09'), (624, '2013-07-09'), (659, '2013-07-09'), (694, '2013-07-09'), (711, '2013-07-09'), (737, '2013-07-09'), (754, '2013-07-09'), (771, '2013-07-09'), (871, '2013-07-09')]

Can anyone please point out what is wrong in my code.

I found the following question pretty much the same as mine and I tried that solution.

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

I have also tried using: chartdata.iteritems but it has had a similar effect. I don't get an error. It never goes in that loop. When I do console.log(chartdata) it shows some parsing error ('& error something') in the browser console but within some junk data I can find my dictionary having the data. But iteritems or just items does not work.

However another problem still persists. Say I do

 alert({{  value  }});

at the javascript side. And value was 'hello' It says as the client side no variable name hello defined. It puts it in whole instead of as a string? What should I do to get this right?

chartData is a list of tuples, not a dict. You need something like this in your template:

{% for row in chartData %}
    console.log("{{ row.0 }}", "{{ row.1 }}");
{% endfor %}

对于第二个问题,请尝试:

alert('{{  value  }}');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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