我将使用ajax+js来实现这一点。我会按照这些原则做点什么(
我没有测试过这个代码
)以下内容:
HTML格式:
<select name="country">
<option value="">Choose a country</option>
<option value="USA">USA</option>
<option value="Mexico">Mexico</option>
<option value="Canada">Canada</option>
</select>
<select name="state" disabled>
<option value="">Choose a state</option>
</select>
JS公司:
$('select[name="country"]').on('change', function() {
var country = $(this).val();
var states = [];
$('select[name="state"] option:gt(0)').remove(); // cleaning: removes all options except the first
if (!(country)) {
$('select[name="state"]').prop("disabled", true);
} else {
$.ajax({
url: "{% url 'get_states' %}",
dataType: "json",
data: {
country: country
},
success: function(data) {
data = JSON.parse(data);
for (var key in data) {
$('select[name="state"]').append(
$('<option>', {
value: key,
text: data[key]
})
);
}
}
});
$('select[name="state"]').prop("disabled", false);
}
});
在url.py中:
url(r'^getstates$', 'myapp.views.get_states', name='get_states'),
在views.py中:
from django.shortcuts import HttpResponse
import json
from myapp.models import Country, State
def get_states(request):
if request.is_ajax():
country = request.GET.get('country', '')
states = State.objects.filter(country__name=country)
state_dict = {}
for state in states:
state_dict[state.pk] = state.name
return HttpResponse(json.dumps(state_dict))
希望这有帮助!