【问题标题】:Django templates how to use tags and template filters to get data from json dictDjango模板如何使用标签和模板过滤器从json dict中获取数据
【发布时间】:2019-09-28 03:58:39
【问题描述】:

我有 dict,可以在这里看到 https://jsoneditoronline.org/?id=a570322381fc45919a7a03ebad78cbee

但从我目前阅读的内容来看,它更有可能是一个字典列表。我正在尝试显示来自标题、描述、作者和类别等字典的数据,但模板标签没有显示我想要的,尝试使用循环但无法访问它

试过这样的循环

{% for items in books %}
    {% for volumeInfo in items %}
        {{ volumeInfo.title }}
    {% endfor %}
{% endfor %}

只有 {{ books.items }} 有效,但它给了我整个 json,但我只需要很少的值。

def api(request):
    books = {}
    if 'books' in request.GET:
        books = request.GET['books']
        url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books
        response = requests.get(url)
        books = response.json()
        print(type(books))
        with open("data_file.json", "w") as write_file:
            json.dump(books, write_file)

    return render(request, 'books/api.html', {'books': books})
{% load get_item from template_filters %}
{% block content %}
  <h2>Google API</h2>
  <form method="get">
    <input type="text" name="book">
    <button type="submit">search on google books api</button>
  </form>
  {% if books %}
    <p>
{% for items in books %}
{% for volumeInfo in items %}
{{ volumeInfo.title }}
{% endfor %}
{% endfor %}
{{ books.items }}
    </p>
  {% endif %}
{% endblock %}

【问题讨论】:

    标签: json django django-templates django-template-filters


    【解决方案1】:

    您需要遵循您拥有的 JSON 的结构。总结一下,数据是这样的:

    {
      "items": [
        {
          "volumeInfo": {
            "title": "Hobbit czyli Tam i z powrotem"
          }
        }
      ]
    }
    

    所以,在模板中:

    {% for item in books.items %}
      {{ item.volumeInfo.title }}
    {% endfor %}
    

    【讨论】:

    • 感谢 Daniel 的澄清和帮助 :)
    猜你喜欢
    • 2013-03-16
    • 2011-08-01
    • 2016-06-28
    • 2020-02-16
    • 2022-01-22
    • 1970-01-01
    • 2017-02-16
    • 2011-09-30
    • 2012-08-28
    相关资源
    最近更新 更多