【问题标题】:Loop results from python into django从 python 循环结果到 django
【发布时间】:2021-04-14 16:45:09
【问题描述】:

我有一个简单的应用程序,可以在远程 URL 中查询城市代码。

views.py

import requests
import json

def home(request):
    return render(request, 'app_sitecode/home.html', {'site_code':''})

def lookup_code(request):
    locode_url = 'https://pkgstore.datahub.io/core/un-locode/code-list_json/data/05f6ccfe0cd03ab51bed07273b982df9/code-list_json.json'
    try:
        city = request.GET.get('city')
        r = requests.get(locode_url)
        raw_data = (json.loads(r.content))
        res = None
        for sub in raw_data:
           if sub['Name'] == city:
              res = sub
              print(res)
              print('')
              #break
              city_code = res['Location']
              country_code = res['Country']
              state = res['Subdivision']
              site_code = country_code + "-" + city_code
        return render(request, 'app_sitecode/home.html', {'site_code':site_code, 'name': city, 'country': country_code, 'state': state})
    except:
        return render(request, 'app_sitecode/home.html', {'cleartext':'', 'city':'INVALID CITY'})

当我查询一个城市时,我得到了有效的回报。例如,我查询斯托顿市。我看到找到了两个 Stoughton(下面的 python 输出)。一个是威斯康星州斯托顿,一个是马萨诸塞州斯托顿。

{'更改':无,'坐标':无,'国家':'美国','日期':'9307','功能':'--3-----','IATA':无, '位置':'SOU','名称':'Stoughton','NameWoDiacritics':'Stoughton','备注':无,'状态':'RQ','细分':'MA'} {'更改':无,'坐标':'4255N 08913W','国家':'美国','日期':'0201','功能':'--3-----','IATA' :无,“位置”:“ZTN”,“名称”:“Stoughton”,“NameWoDiacritics”:“Stoughton”,“备注”:无,“状态”:“RL”,“细分”:“WI”}

我遇到的困难是如何在 html 文件中循环结果。目前,html 文件只打印找到的最后一个条目。

home.html

{% block content %}
<!doctype html>
<html lang="en">
   <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<form action="{% url 'lookup_code' %}" autocomplete="off">
<div class="container">
<br>
    <!-- Text input-->

<form>
  <div class="form-row align-items-center">

    <div class="col-sm-3 my-1">
      <label class="sr-only" for="inlineFormInputGroupUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">City</div>
        </div>
        <input type="text" id="city" name="city" class="form-control" id="inlineFormInputGroupUsername" placeholder="">
      </div>
    </div>
    <div class="col-auto my-1">
      </div>
    <div class="col-auto my-1">
      <input type="submit" class="btn btn-primary btn-small" value="Find It">
    </div>
  </div>
</form>


<br>
<h3> {{ site_code }} </h3>
<p><small class="text-muted">{{ name }}, {{ state }} {{ country}} </small></p>
</div>
</form>

</body>
{% endblock %}

我尝试了一个 jijna2 for 循环,但我似乎无法让它工作(从上面的 home.html 中删除)。这是我尝试过的循环-

{% for site in site_code %}
 {{ site }}
{% endfor %}

没有循环的结果-

我想要的是所有 Stoughton 网站的列表,而不仅仅是最后一个。感谢您的宝贵时间。

home.html 中的循环结果

【问题讨论】:

  • 你为什么不把你在循环中计算的这些site_code 放入一个 list 并将这个列表传递到上下文中......(因为它是你传递site_code 当然只会传递循环的最后一个变量,因为它是你要覆盖的同一个变量)

标签: html django django-templates


【解决方案1】:

这里可以使用list comprehension

def lookup_code(request):
    locode_url = 'https://pkgstore.datahub.io/core/un-locode/code-list_json/data/05f6ccfe0cd03ab51bed07273b982df9/code-list_json.json'
    try:
        city = request.GET.get('city')
        r = requests.get(locode_url)
        raw_data = (json.loads(r.content))
        site_codes = [
            {
                "city_code": res['Location'],   
                "country_code": res['Country'],
                "state": res['Subdivision'],
                "site_code": "%s-%s" % (res['Country'],res['Location']),
            } 
            for res in raw_data if res['Name'] == city
        ]
        return render(request, 'app_sitecode/home.html', {'site_codes': site_codes})
    except:
        return render(request, 'app_sitecode/home.html', {'cleartext':'', 'city':'INVALID CITY'})

模板:

{% for site in site_codes %}
    {{ site.site_code }}, {{ site.state }}
{% endfor %}

【讨论】:

  • 正是我想要的。我知道必须有更聪明的方法。谢谢!
  • @CollinClark,很高兴为您提供帮助 ?!
猜你喜欢
  • 2017-09-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多