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})
上圖: