Python form drop down options populated by sql

走远了吗. 提交于 2021-02-08 07:56:37

问题


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. 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. 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:

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

回答1:


How much detail do you need here. You have the SQL query but no object storing it. Are you familiar at all with running SQL queries from python? If so then a simple for loop and string formatting will build the options from the database result.

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. I personally use SQLAlchemy ORM with Python.



来源:https://stackoverflow.com/questions/29549714/python-form-drop-down-options-populated-by-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!