简体   繁体   English

在表单提交python / flask后保留原始选定的值

[英]keep original selected values after form submit python/flask

I have a two pronged question and would appreciate any advice. 我有一个双管齐下的问题,并希望得到任何建议。

1) I have a flask template with multiple forms in it. 1)我有一个烧瓶模板,里面有多个表格。 Each form presents the user with a list that is dynamically generated from a mongodb query. 每个表单向用户显示一个从mongodb查询动态生成的列表。

name_list = [p['name'] for p in posts.find({'type': "server"})]
name_list.insert(0, "select")

This is then refernced in my html template (thank you again to the person who helped me with this loop on a previous question) 然后在我的html模板中引用它(再次感谢那个帮我解决上一个问题的人)

      <select name="option" id="myselect" onchange="this.form.submit()">
      {% for x in server_list %}
      <option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
      {% endfor %}

This selection is then passed back to python to be used in another db query and then present the user with another dropdown select box. 然后将此选择传递回python以在另一个db查询中使用,然后向用户显示另一个下拉选择框。 However when the first form is submitted, the new page render means that that value is now lost on the html and appears blank. 但是,当提交第一个表单时,新页面呈现意味着该值现在在html上丢失并显示为空白。 Is there a way to keep this choice persistent so when after the new page render it still appears? 有没有办法让这个选择保持不变,所以在新页面渲染之后它仍然会出现?

2) Secondly, I would like to keep a running list of what options the user makes, however given the if, elif structure I'm using that variable looses state and can no longer used. 2)其次,我想保留用户所做选项的运行列表,但是给定if,elif结构我正在使用该变量松散状态并且不能再使用。 Eventually I would like to present the user with two sets of these dropdown menus to generate to final db querys that I can compare and return the difference, however I can only do this if I can keep state of these values generated in the loops. 最后,我想向用户提供两组这些下拉菜单,以生成最终的db查询,我可以比较并返回差异,但是如果我能保持循环中生成的这些值的状态,我只能这样做。

Please see full code below: 请参阅下面的完整代码:

python: 蟒蛇:

from flask import render_template
from flask import request
from flask import Response
from app import app
from pymongo import MongoClient

@app.route('/', methods=['POST','GET'])
@app.route('/index', methods=['POST','GET'])

def index():
    user = {'name': 'Bob'}

    client = MongoClient('mongodb://localhost:27017/')
    db = client['test-database']
collection = db.test_collection
name_list = []
posts = db.posts
name_list = [p['name'] for p in posts.find({'type': "server"})]
name_list.insert(0, "select")
select_list = []

#if request.form['submit'] == 'myselect':
if request.method == 'POST' and request.form.get('option'):
    choice = request.form.get('option')
    select_list.append(choice)
    sub_name_list = [q['type'] for q in posts.find({'name': choice})]
    return render_template("index.html",
                    sub_server_list=sub_name_list)


elif request.method == 'POST' and request.form.get('option1'):
    choice1 = request.form.get('option1')
    select_list.append(choice1)
    return render_template("index.html",
                    title='Database selector',
                    user='Person',
                    choiced=choice1,
                    total_choice=select_list)


return render_template("index.html",
                       title='Database selector',
                       user='Person',
                       server_list=name_list)

html/jinja: HTML /神社:

<html>
  <head>
    <title>{{ title }} - Test</title>
  </head>
  <body>
    <h1>Hi, {{ user }}!</h1>


      <h2>Database selector</h2>
        <h3><table><form action="" method="post">
          <td>
          <label>Select1 :</label>
            <!--<select name="option" width="300px">-->
              <select name="option" id="myselect" onchange="this.form.submit()">
              {% for x in server_list %}
              <option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
              {% endfor %}

            </select>

          </td>

            </form></table></h3>

        <h3><table><form action="" method="post">
          <td>
            <label>Select2 :</label>
              <select name="option1" id="sub_myselect" onchange="this.form.submit()">
              {% for y in sub_server_list %}
              <option value="{{ y }}"{% if loop.first %} SELECTED{% endif %}>{{ y }}</option>
              {% endfor %}
          </td>

        </form></table></h3>

  <h3>Here is the choice: {{ choiced }}</h3>
  <h3>Here is the choice: {{ total_choice }}</h3>
  </body>
</html>

Any pointers or ideas would be greatly appreciated. 任何指针或想法将不胜感激。

  1. Have a look at sessions . 看看会议 You might have to change the way you store your data though, maybe by finding an appropriate name for choice and choice1 and storing them in a dict . 您可能必须更改存储数据的方式,可能是通过找到适当的名称进行choicechoice choice1并将它们存储在dict中

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

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