【问题标题】:Django html issue with templates and views模板和视图的 Django html 问题
【发布时间】:2015-06-02 17:36:49
【问题描述】:

我的问题是我似乎无法将字典翻译成表格,这是错误:

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

HTML 代码:

<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 代码:

~~~~  There's stuff here but it shouldn't be important. ~~~~ 
return render(request,'hackathon/SteamAPI.html', 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},

【问题讨论】:

标签: python html django


【解决方案1】:

Django 模板不支持[] 索引。而不是

game["appid"] 

你应该使用

game.appid

这同样适用于game.namegame.playtime_forever

作为不相关的说明,您还应该关闭 for 循环:

</tr>
{% endfor %}
</table>

【讨论】:

  • 嗯我现在有这个错误,不确定模板有什么问题:模板渲染期间出错在模板/home/marco/repos/django-hackathon-starter/hackathon_starter/hackathon/templates/hackathon/ SteamAPI.html,第 10 行错误无效的块标签:'endblock',预期为'empty'或'endfor'
  • @Marorin 这是一个不相关的错误;查看我的更新答案
  • 如果答案解决了你原来的问题,你应该把它作为一个新问题发布。这样,未来的访问者可以利用问题和答案,其他人也可以回答您的后续问题。
【解决方案2】:

在 Django 模板中应该以这种方式访问​​字典。

选择 = {'key1':'val1', 'key2':'val2'}

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}
</ul>

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 2016-04-27
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2011-09-18
    • 2012-05-26
    相关资源
    最近更新 更多