如何通过flask中的url路由获取下拉值并更改页面?

2024-06-08 02:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下拉列表中选择一个值并相应地显示网页。目前,我可以通过在URL末尾键入下拉列表的每个值来访问它。我到底缺了什么?当我在浏览器中键入/metadata/table_name1metadata/table_name2时,我可以访问它。但是当我从下拉列表中选择选项时,我无法得到它。下拉列表应该重定向到metadata/drop_down_value。在

我已经通过打印出单独的url路由链接进行了测试。通过点击链接,它就起作用了。我需要从下拉列表中选择。在

观点:

@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)

形式:

^{pr2}$

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>

Tags: nameform列表fordbgettableuri
1条回答
网友
1楼 · 发布于 2024-06-08 02:43:58

您需要一点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

相关问题 更多 >

    热门问题