Django:将后台返回的数据填充到select下拉框中

时间:2022-01-23 04:16:22

select选择框如下:

<select data-placeholder="选择项目..." class="form-control" name="update_project_name" id="update_project_name">
  <option value="">请选择项目</option>
  {% for key,value in project.items %}
  <option value="{{ value }}" hassubinfo="true">{{ key }}</option>
{# <option value="120000" hassubinfo="true">天津</option>#}
{# <option value="130000" hassubinfo="true">河北省</option>#}
  {% endfor %}
</select>

后台通过查询数据库,然后组装数据格式为字典格式,返回数据,前台通过{% for key,value in project.items %}遍历该字典,取得对应的键值对

def smoke_test_case(request):
project_data = {}
db = pymysql.connect("localhost", "root", "***", "****", charset='utf8')
cursor = db.cursor()
sql = 'SELECT project_name,project_code FROM project'
cursor.execute(sql)
results = cursor.fetchall()
print list(results)
for i in list(results):
project_data[i[0]]=i[1]
print project_data
return render(request, "showcase/smoke_test_case.html", {'project': project_data})

上图:

Django:将后台返回的数据填充到select下拉框中