1

My issue is that I can't seem to translate the dictionary into a table here's the error:

Could not parse ["appid"] from 'game[''appid"] 

HTML code:

<table>
<tr>
  <th>Game ID</th>
  <th>Game Name</th>
  <th>Hours Played</th>
</tr>
{% for game in games %}
{# each game object is a dictionary with "appid", "name " and "playtime_forever" keys #}
<tr>
  <td>{{ game["appid"] }}</td>
  <td>{{game["name"]}}</td>
  <td>{{ game["playtime_forever"] }}</td>
</tr>
</table>

views.py code:

~~~~  There's stuff here but it shouldn't be important. ~~~~ 
return render(request,'hackathon/SteamAPI.html', game)

When I run the server it shows:

game:

[{u'appid': 4000, 
  u'has_community_visible_stats': True, 
  u'img_icon_url': u'd9101cbeddcc4ff06c7fa1936c3f381b0bbf2e92',
  u'img_logo_url': u'dca12980667e32ab072d79f5dbe91884056a03a2', 
  u'name': u"Garry's Mod", 
  u'playtime_forever': 0},
Selcuk
  • 57,004
  • 12
  • 102
  • 110
Marorin
  • 167
  • 3
  • 12
  • This question has been asked many times before. http://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template – Akash Deshpande Mar 29 '15 at 19:55

2 Answers2

3

Django templates do not support [] indexing. Instead of

game["appid"] 

you should use

game.appid

The same applies for game.name and game.playtime_forever

As an unrelated note, you should also close your for loop:

</tr>
{% endfor %}
</table>
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Hmmm I now have this error, not sure whats wrong with the template: Error during template rendering In template /home/marco/repos/django-hackathon-starter/hackathon_starter/hackathon/templates/hackathon/SteamAPI.html, error at line 10 Invalid block tag: 'endblock', expected 'empty' or 'endfor' – Marorin Mar 29 '15 at 20:18
  • @Marorin It is an unrelated error; see my updated answer – Selcuk Mar 29 '15 at 20:24
  • If the answer solved your original problem you should post this as a new question. This way, future visitors can make use of the question and the answer, and someone else can also answer your follow up question. – Selcuk Mar 29 '15 at 20:41
0

Dictionary should be accessed this way in Django Templates.

choices = {'key1':'val1', 'key2':'val2'}

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}
</ul>
Akash Deshpande
  • 2,583
  • 10
  • 41
  • 82