1

I have a simple application that queries a remote URL for a city code.

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'})

When I query for a city, I get valid returns. For example I query the city Stoughton. I see that two Stoughton's were found (python output below). One is Stoughton, WI and one is Stoughton, MA.

{'Change': None, 'Coordinates': None, 'Country': 'US', 'Date': '9307', 'Function': '--3-----', 'IATA': None, 'Location': 'SOU', 'Name': 'Stoughton', 'NameWoDiacritics': 'Stoughton', 'Remarks': None, 'Status': 'RQ', 'Subdivision': 'MA'}

{'Change': None, 'Coordinates': '4255N 08913W', 'Country': 'US', 'Date': '0201', 'Function': '--3-----', 'IATA': None, 'Location': 'ZTN', 'Name': 'Stoughton', 'NameWoDiacritics': 'Stoughton', 'Remarks': None, 'Status': 'RL', 'Subdivision': 'WI'}

The struggle I am having is how to loop the results in the html file. Currently the html file prints only the last entry found.

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

I've tried a jijna2 for loop, but I can't seem to get it working (removed from home.html above). Here is the loop I tried-

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

Results without the loop-

enter image description here

What I would like is a list of all the Stoughton sites, not just the last one. Thank you for your time.

Results with the loop in home.html

enter image description here

1
  • Why don't you put these site_code that you calculate in the loop into a list and pass this list into the context... (As it is you passing site_code will of course pass only the last variable of the loop, because it is the same variable you are overwriting) Commented Apr 14, 2021 at 17:12

1 Answer 1

1

Here can be used a 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'})

template:

{% for site in site_codes %}
    {{ site.site_code }}, {{ site.state }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I was looking for. I knew there had to be a smarter way. Thank you!
@CollinClark, Happy to help 👍!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.