Django:根据父下拉框选择更新子下拉框选项

2 投票
2 回答
829 浏览
提问于 2025-04-18 12:54

有没有人知道怎么让一个“子”下拉框的选项根据“父”下拉框的选择在管理页面上自动更新呢?

问题:我有两个下拉框。在第一个下拉框里,我选择一个汽车品牌。选择了汽车品牌后,我希望“子”下拉框的选项能更新为该品牌的车型。

我在我的模型中正确使用了外键(ForeignKey),所有模型也都没问题,但如果你能给我一些指导来解决这个问题,我会非常感激。谢谢!

解决方案:我使用了 smart_selects。 https://github.com/digi604/django-smart-selects

2 个回答

0

你可以通过JavaScript和元素操作来实现这个功能:

首先,把汽车型号保存到JavaScript的变量里,比如:

<script type="text/javascript">
var porsche = {{ porsche|safe }};
var vw = {{ vw|safe }};
</script>

然后在你的JavaScript代码中,可以为父级选择框指定一个新的变化方法:

$('#parent_select').change(function(){
    changeCars();
});

这个函数可以用来操作子选择框:

var newCarList = [];
val =$('#parent_select').val();
if (val=='porsche'){
    newCarList = porsche;
}
else if (val == 'vw'){
    newCarList = vw;
}
else{
    //some Error handling
}

select = document.getElementById('child_select');
while (select.firstChild) {
select.removeChild(select.firstChild);
// to remove all previously added childs (option fields)
}

for (var i = 0; i < newCarList.length; i ++){
    var opt = document.createElement('option');
    opt.value = newCarList[i];
    opt.innerHTML = newCarList[i];
    select.appendChild(opt);
    //append all new Childs to the child_select
}

这种方法是可行的,但速度比较慢,因为操作对象并不是最快的方式。另一种方法是创建不同的子选择框,然后通过显示或隐藏来只显示与父选择框的值相对应的那个。

0

我解决了我的问题。我使用了Django的smart_selects这个工具。你可以在github上找到它,地址是github.com/digi604/django-smart-selects。

撰写回答