假设您在一系列选择框中谈论这样做:
创建两个视图,一个返回包含给定区域的部门的响应。另一个做同样的事情,但对于 Departamento 中的 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>
你会使用一些像(在 jQuery 中)这样的 javascript:
// 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 相同的操作。
您可能还想做一些事情,比如在没有可用选项时禁用字段,并处理没有返回 departamentos 或 municipios 的情况。