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

时间:2014-07-11 07:39:03

标签: python django select admin box

是否有人知道如何根据管理页面中“父”选择框的选择自动更新“子”选择框的选项?

问题:我有两个选择框。在第一个我选择的例如一个汽车品牌。一旦我选择了汽车品牌,我想要“孩子”选择框选项来更新该品牌的型号。

我在我的模型中正确使用ForeignKey并且所有模型都是正确的但如果你能给我一些指导来解决这个问题,我将不胜感激。谢谢!

已解决:我使用过smart_selects。 https://github.com/digi604/django-smart-selects

2 个答案:

答案 0 :(得分:0)

您可以使用JavaScript和Elementmanipulation执行此操作:

将汽车模型保存到JavaScript Vars:即

<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
}

这种可能性会起作用但速度很慢,因为对象操作不是最快的方法。 另一种可能性是创建不同的子选择并使用show / hide仅根据parent_select的值显示正确的子选项。

答案 1 :(得分:0)

我已经解决了我的问题。我使用了Django smart_selects。 github.com/digi604/django-smart-selects

相关问题