假設你正在談論一系列的選擇框這樣做:
創建兩個觀點,其中一個返回一個包含Departamentos一個給定區域的響應。其他不相同,但對於Municipios在阿雅
# views.py
from django.core import serializers
def departamentos_por_region(request, region_id):
region = get_object_or_404(Region, id=region_id)
departamentos = Departamento.objects.filter(region=region)
return render_to_reponse("format_as_option_list.html",
{'departamentos': departamentos})
def municipios_por_departamento(request, departamento_id):
# basically the same as above
我假設您填寫的初始頁面視圖中的地區選擇框,所以不需要作特殊視圖。
模板應該格式化爲html選項列表。
假設那麼在初始頁面視圖中的HTML看起來像:
<select id='regions'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
</select>
<select id='departamentos'>
</select>
<select id='municipios'>
</select>
你會使用一些JavaScript等(jQuery的):
// this isn't tested code and likely contains an error or two
$('#regions').change(function(){
// Region has changed, so reset Departamentos and Municipios
$('#departamentos').html("")
$('#municipios').html("")
// now update the departamentos
$.get('/ajax/departamentos_por_region/' + $('#regions').val(),
function(data) {
('#departamentos').html(data)
};
);
});
執行相同的Municipios爲爲Departamentos。
您可能還想在停用字段沒有可用選項時處理這些問題,並處理沒有退回或離開的情況。