提问者:小点点

基于Django中的事件呈现字典的键值


我在Django应用程序的。html文件中有两个下拉列表,分别是:

        <select class="form-control" id="exampleFormControlSelect1">

          <option>op1</option>


        </select>
        <select class="form-control" id="exampleFormControlSelect2">

          <option>opt1</option>

        </select>

Django views.py中呈现了一个字典。我希望键在第一个下拉列表中显示为选项,并且无论何时选择键,相应的值都需要在第二个下拉列表中显示。我尝试了一些js和jina模板,但没有成功。我如何实现它? 我尝试了以下JS:

function myFunction() {

  var dict=[];
  dict.push("{{Names}}");
  alert(Object.keys(dict));

}

我退回的字典是这样的:

Names={1991:["cat & dog","Mat-bat","task force"],1992:["average life span!","text-user"]}

输出:0 Django views.py:

def home(requests):
    return render(requests,'home/index.html',{"Names":getNames()})

共1个答案

匿名用户

您可以使用Django的模板呈现来填充第一个下拉列表,类似于:

<select class="form-control" id="exampleFormControlSelect1">
    {% for key, values in yourdict %}
    <option value={{ values }}>{{ key }}</option>
    {% endfor %}
</select>

确保将您的dictionary变量传递给模板,并用您的dictionary变量的调用替换“yourdict”。

然后需要使用javascript/jquery填充第二个下拉列表。 在第一个下拉列表中添加onchange函数:

<select class="form-control" id="exampleFormControlSelect1" onchange="populateSecond()"></select>

然后在JS中可以定义该函数:

function populateSecond() {
   var select1 = document.getElementById("exampleFormControlSelect1");       
   var select2 = document.getElementById("exampleFormControlSelect2");       
   var selectedValue = select1.options[select1.selectedIndex].value;
   selectedValue.forEach(function(element){       
       select2.appendChild(element);  
   }     
}

这要求您在第一个下拉列表中存储的值被识别为数组。 我不确定他们是否会手忙脚乱,但如果不是,您可能必须使用split()方法将selectedValue的值从字符串转换为数组