Sohaib
Sohaib

Reputation: 4694

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.

Edit: Problem turned out to be that I was using integers as a dictionary key

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?

Upvotes: 0

Views: 2178

Answers (2)

acidjunk
acidjunk

Reputation: 1880

For your second question, try:

alert('{{  value  }}');

Upvotes: 0

Scott Woodall
Scott Woodall

Reputation: 10676

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 %}

Upvotes: 1

Related Questions