簡體   English   中英

如何在燒瓶中通過URL路由獲取下拉值並更改頁面?

[英]How to get a drop down value and change the page by url routing in flask?

我想從下拉列表中選擇一個值,並相應地顯示網頁。 目前,我可以通過在URL的末尾鍵入下拉列表來訪問每個值。 我到底在想什么? 在瀏覽器中輸入/metadata/table_name1 metadata/table_name2時,我可以訪問它。 但是,當我從下拉菜單中選擇選項時,我將無法獲得它。 下拉列表應重定向到metadata/drop_down_value

我已經通過打印出單獨的網址路由鏈接進行了測試。 通過單擊鏈接,它可以工作。 我需要從下拉列表中進行選擇。

瀏覽次數:

@app.route('/metadata', methods=['GET', 'POST'])
def metadata():
    cols = None
    table = None
    db_uri = session.get('db_uri', None)
    eng = create_engine(db_uri)
    insp = reflection.Inspector.from_engine(eng)
    tablenames = insp.get_table_names()
    form = SelectTableForm()
    form.table_name.choices = tablenames
    cols = insp.get_columns(table_name=tablenames[0])
    eng.dispose()
    return render_template('tables.html', cols=cols, table=tablenames[0], form=form)

@app.route('/metadata/<table>', methods=['GET', 'POST'])
def select_table(table):
    form = SelectTableForm()
    db_uri = session.get('db_uri', None)
    eng = create_engine(db_uri)
    insp = reflection.Inspector.from_engine(eng)
    tablenames = insp.get_table_names()
    form.table_name.choices = tablenames
    cols = insp.get_columns(table_name=table)
    return render_template('tables.html', cols=cols, table=table, form=form)

形成:

class SelectTableForm(FlaskForm):

    table_name = SelectField(label='Table name', choices=[], coerce=int)

Jinja html:

<!-- This works -->
{% for table in form.table_name.choices %}
    <a href="{{ url_for('select_table', table=table) }}">{{ table }}</a>
{% endfor %}

<!-- This does not -->

<form action="">
    <select name="tables" method="POST" type="submit">
      {% for table in form.table_name.choices %}
          <option value="{{ url_for('select_table', table=table) }}">{{ table }}</option>
      {% endfor %}
    </select>
</form>

<table>
    <tr>
        <th>table</th>
        <th>name</th>
        <th>type</th>
        <th>nullable</th>
        <th>default</th>
        <th>autoincrement</th>
        <th>comment</th>
    </tr>
    {% for col in cols %}
        <tr>
        <td>{{ table }}</td>
        {% for val in col.values() %}
            <td>{{ val }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>

您需要一些js,在其中將當前頁面的url設置為select元素中所選選項的值: onchange="location = this.value;"

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template_string('''
        <select name="form" onchange="location = this.value;">
          {% for table in tables %}
              <option value="{{ url_for('select_table', table=table) }}">{{ table }}</option>
          {% endfor %}
        </select>
''', tables = ['a', 'b'])


@app.route('/select_table/<table>', methods=['GET', 'POST'])
def select_table(table):
    return table

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM