首页 > 解决方案 > 根据Django中的事件渲染字典的键值

问题描述

我的 Django 应用程序的 .html 文件中有两个下拉列表,即:

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

          <option>op1</option>


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

          <option>opt1</option>

        </select>

A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template但没有运气。我怎样才能实现它?我尝试了以下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()})

标签: javascripthtmlpython-3.xdjangodjango-rest-framework

解决方案


您可以使用 Django 的模板渲染来填充第一个下拉列表,例如:

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

确保将您的字典变量传递给模板,并将“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 的值从字符串转换为数组


推荐阅读