[Fixed]-Not able to implement a dynamic dropdown list in Django

1👍

There are two solutions:

Solution 1:

use a for loop:

country_objs['{{country|escapejs}}'] = [{% for city in cities %}"city",{% endfor %}];

Solution 2:

Switch the line:

citiesByCountry[country.Name] = cities

for:

citiesByCountry[country.Name] = json.dumps(cities)

to encode to json, and then in the template:

country_objs['{{country|escapejs}}'] = {{cities|safe}};

Obs regarding solution 2:

You can’t have the single quotes around the variable

'{{cities|safe}}';

in the second solution, or else when you add the list ['City1', 'City2', 'City3'] you’re gonna have:

'['City1', 'City2', 'City3']'
👤Fabio

0👍

I think you want to remove the |escapejs filter for the part you want to be parsed in JavaScript. You might even find you need |safe, but you should be certain that you have control over what gets output there before considering that.

var country_objs = {};
{% for country, cities in citiesByCountry.items %}
country_objs['{{country|escapejs}}'] = {{cities|safe}};
{% endfor %}

For the updating part, this should work:

function updateCities(country) {
    var $cities_select = $("#cities");
    $(country_objs[country]).each(function(key, value) {   
        $('#cities').append($("<option></option>")
                    .attr("value",key)
                    .text(value)); 
    });
}

$('#sel1').change(function() {
    updateCities(this.value);
});

Credit due in part to this answer https://stackoverflow.com/a/171007/823020.

The above is missing an initial setting, which you could either do in templating or JavaScript. For JavaScript, you could insert another updateCities($('#cities).val());.

The above also appends every time, instead of resetting the options to an empty list. This is left as an exercise for the reader.

Suggestion 1: You didn’t discuss this, but your initial query would be better done something like this:

# the following may differ based on your foreign key's related_name attribute
countries = Country.objects.filter(Enabled=True).select_related('city_set')
for country in countries:
    citiesInCountry = country.city_set.values_list('name', flat=True)

This would all be a single query. However you’d need to rethink about the ‘active’ flag, or how to achieve that if you still need it.

Suggestion 2: To be honest, it might be better in general to wrap it up in json. In your view:

import json
countries_json = json.dumps(citiesByCountry)

and then in the template:

var country_objs = {{ citiesByCountry|safe }};

Leave a comment