Здесь приведена модификация кода из формы билета betspire.com. Этот фрагмент кода зависит от загрузки jQuery.
Вот необходимый вам javascript:
function update_select(select, data) {
select.find('option').remove();
select.append($('<option value="">-------</option>'));
for (var i in data) {
select.append($('<option value="'+data[i][0]+'">'+data[i][1]+'</option>'));
}
}
$('select[name=island_group]').live('change', function(e) {
$.get(
'{% url island_name_choices_for_island_group %}',
{
'island_group': $(this).val(),
},
function(data, textStatus, jqXHR) {
update_select($('select[name=island_name]'), data);
},
'json'
);
});
Добавить к URL:
url(
r'island_name/choices/$',
'island_name_choices_for_island_group', {
}, 'island_name_choices_for_island_group',
),
Добавить в просмотры:
from django.utils import simplejson
from models import *
def island_name_choices_for_island_group(request, qs=None):
if qs is None:
# Change the default QS to your needs
# (you didn't specify it)
qs = Island.objects.all()
if request.GET.get('island_group'):
# assuming your Island model has an FK named island_group to model IslandGroup
qs = qs.filter(island_group__pk=request.GET.get('island_group'))
results = []
for choice in qs:
results.append((choice.pk, choice.name))
return http.HttpResponse(simplejson.dumps(results))
Пожалуйста, дайте мне знать, если у вас возникнут какие-либо проблемы.