Naftuli Kay
Naftuli Kay

Reputation: 91660

Is there a way to dump all states/provinces/territories?

I'm currently writing a country/territory input form. You know, something like this:

enter image description here

I haven't really found another good way to do this, so here's what I'm doing. I'm using django-countries, and simply doing a for loop in my template to dump all of the countries out to the HTML:

def myview(request):
    from django_countries import countries
    return direct_to_template(request, "template.html", { "countries": countries.COUNTRIES })

{% for country in countries %}
    <option value="{{country.0}}">{{country.1}}</option>
{% endfor %}

Now comes the tricky part. I'd like to essentially take as much advantage of native controls as possible, so I'm looking to do something like this:

{% for country in territory_countries %}
    <optgroup label="{{country.0}}">
        {% for territory in country.1 %}
            <option value="{{territory.0}}">{{territory.1}}</option>
        {% endfor %}
    </optgroup> 
{% endfor %}

Clear as mud, right?

The first COUNTRIES list looks like this:

COUNTRIES = (
    ('US',  'United States'),
)

I'd like something that looks like this:

TERRITORIES = (
    ('US',
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
    ),
)

It doesn't have to look exactly like that, but it'd be nice if I could fit it into my design.

Am I going about this wrong? Is there a better, smarter way of doing this? Is there a Django module which is much smarter about this and uses actual models in the database?

It'd be much nicer to do:

countries = Country.objects.all()

<select id="countries">
    {% for country in countries %}
        <option value="{{country.abbr}}">{{country.name}}</option>
    {% endfor %}
</select>

<select id="territories">
    {% for country in countries %}
        {% if country.territories %}
            <optgroup label="{{country.abbr}}">
                {% for territory in country.territories %}
                    <option value="{{territory.abbr}}">{{territory.name}}</option>
                {% endfor %}
            </optgroup>
        {% endif %}
    {% endfor %}
</select>

Is there something to help me out with this? Should I just say "to heck with it" and build a Django module to do what I want?

Upvotes: 1

Views: 365

Answers (1)

Naftuli Kay
Naftuli Kay

Reputation: 91660

Yep, I definitely built a Django library to deal with this issue: django-locality

Reap the benefits of my suffering.

Upvotes: 1

Related Questions