2011-11-24 99 views
1

我目前正在撰寫國家/地區輸入表格。要知道,這樣的事情:有沒有辦法轉儲所有州/省/地區?

enter image description here

我還沒有真正找到另一個好辦法做到這一點,所以這裏是我在做什麼。我使用的django-countries,並簡單地做一個for循環在我的模板傾倒所有國家的出到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 %} 

現在到了棘手的部分。我希望儘可能多地利用原生控件,所以我期望做這樣的事情:

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

清除泥土,對不對?

第一COUNTRIES名單如下:

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

我想要的東西,看起來像這樣:

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

它沒有看起來完全一樣,但它」如果我能適應我的設計,我會很高興。

我是否在談論這個錯誤?有沒有更好,更聰明的做法?是否有一個更聰明的Django模塊,並在數據庫中使用實際的模型?

這將會是好得多的事情:

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> 

有什麼幫助我這個?我應該只是說「聽它」,並建立一個Django模塊來做我想要的嗎?

回答

1

是的,我肯定建一個Django庫來解決這個問題:django-locality

粒我的痛苦的好處。