简体   繁体   English

SQL填充的Python表单下拉选项

[英]Python form drop down options populated by sql

This is my first post. 这是我的第一篇文章。 I am fairly new to programming. 我是编程新手。 I am attempting to build a html form in Python which contains a drop down. 我正在尝试在Python中构建一个包含下拉列表的html表单。 The drop down options, I currently have hard coded, but want to populate the options from sql, so that it will be dynamically changing if the database is updated for the options. 我目前已对下拉选项进行了硬编码,但希望从sql中填充选项,因此如果为选项更新了数据库,则它将动态更改。 I also must mention that this drop down is being used as a search/filter for a data table which is also populated from the database. 我还必须提到,此下拉列表被用作对数据表的搜索/过滤器,该数据表也从数据库中填充。

Please help with any suggestions. 请帮助任何建议。

Hard Coded dropdown: 硬编码下拉列表:

<div class="dropdown col-lg-2">
  <label for="form_status" id="form_status">STATUS</label>
    <select class="form-control input-sm" id="form_status" name="form_status">
      <option {% if var_status == ""%}selected="selected"{% endif %} value=""></option>
      <option {% if var_status == "1001"%}selected="selected"{% endif %} value="1001">Active</option>
      <option {% if var_status == "1018"%}selected="selected"{% endif %} value="1018">Obsolete</option>
    </select>
</div>

Code Behind for search filter 搜索过滤器背后的代码

if request.method == 'GET':
    var_status = ''

if request.method == 'POST':

    if 'form_status' in request.POST and request.POST['form_status']:
        var_status = request.POST['form_status']

SQL Query: SQL查询:

SELECT  DISTINCT "CODE" AS status_code, "LONGDESC" AS status FROM v_status WHERE "CODE" =1001 OR "CODE" = 1018 ORDER BY "CODE"


1001 | Active
1018 | Obsolete

How much detail do you need here. 您需要多少细节。 You have the SQL query but no object storing it. 您有SQL查询,但没有存储它的对象。 Are you familiar at all with running SQL queries from python? 您完全熟悉从python运行SQL查询吗? If so then a simple for loop and string formatting will build the options from the database result. 如果是这样,那么简单的for循环和字符串格式将根据数据库结果构建选项。

for line in sqlResponse:
    print("<option value='%s'>%s</option>" % (
        str(line.status_code), str(line.status)
    )

If not, then without knowing what your database is and what library you intend to use there's no easy answer other than look around at basic SQL in python tutorials first and decide on a framework/library that works with your database. 如果不是这样,那么除了不了解您的数据库是什么以及打算使用哪个库,除了首先在python教程中浏览基本SQL并确定适用于数据库的框架/库之外,没有其他简单的答案。 I personally use SQLAlchemy ORM with Python. 我个人将SQLAlchemy ORM与Python结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM