I am trying to parse a JSON object to Django template so that I can parse this json object to javascript.
Here how my view creates and parse the json object to the template:
countries = Country.objects.filter(Enabled=True)
citiesByCountry = {}
for country in countries:
citiesInCountry = City.objects.filter(Enabled=True, Country=country)
cities = []
for city in citiesInCountry:
cities.append(city.Name)
citiesByCountry[country.Name] = cities
context = {'citiesByCountry': json.dumps(citiesByCountry)}
return render(request, 'index.html', context)
Now I would like to retrieve all the keys (which will be countries) to my template this way:
{% for country in citiesByCountry%}
<option>{{ country }}</option>
{% endfor %}
But what I get is an option for each character in strings instead of the country name as a whole.
I tried to use .item1 but this didn't work either.
I don't show JavaScript code in my example above as the intent of the question is how to parse and retrieve strings from a JSON object. I need to process this data using javascript later. In specific once the user change country I would like to populate another dropdown that will handle the cities, and therefore I thought to use JSON and Javascript to achieve that, as I don't want to refresh the page on each change.
Any help?
citiesByCountryto JSON? Just pass it as a dict to context likecontext = {'citiesByCountry': citiesByCountry}and it should work.