如何使用url_for将Jinja变量传递到烧瓶中

时间:2020-08-15 10:20:31

标签: python html flask jinja2

我有一个HTML表单,如下所示:

             <form action="{{ url_for('home_blueprint.tabledata', tablename = col )}}" method="post">

                <select name="tables" placeholder="Table" id="tables" size=3>
                      {% for col in column_names %}
                      <option value = "{{ col }}">{{ col }}</option>
                      {% endfor %}
                </select>

                <button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
            </form>

基本上,上面的表单显示项{{col}}的下拉列表。我希望从上面的列表中选择并提交的项目(例如:'tablename')出现在我的URL中,例如www.example.com/tabledata/tablename

我的烧瓶代码在这里:

     @blueprint.route('/tabledata/<tablename>', methods=['GET', 'POST'])
     @login_required

     def tabledata(tablename):

         return render_template('index.html', tablename=tablename)

换句话说,我想使用url_for将这种形式的变量传递给flask。

我该怎么做?预先谢谢你!

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。我会选择最基本的(至少对我来说)。

您只需要调整功能,以便如果有人提交了GET请求,他/她将获得下拉列表,并且如果用户提交了POST请求,则获取POST数据并重定向他/她转到另一个网址,即动态网址。

因此您的烧瓶代码变为:

@blueprint.route('/tabledata/<tablename>', methods=['GET', 'POST'])
@login_required
def tablename(tablename):
    return "Hi"

@blueprint.route('/tabledata')
@login_required
def tabledata():
    if request.method == 'GET':
        return render_template('index.html', column_names=['abc', 'def', 'ghi']) # Column names were added by me, ignore it
    elif request.method == 'POST':
        data = request.form.get("tables")
        return redirect(url_for('tablename', tablename=data))

对表单操作进行一点改动:

<form action="{{ url_for('home_blueprint.tabledata')}}" method="POST">

        <select name="tables" placeholder="Table" id="tables" size=3>
              {% for col in column_names %}
                <option class="column" value="{{ col }}">{{ col }}</option>
              {% endfor %}
        </select>
    
        <button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
</form>

现在,如果您从下拉菜单中单击一个选项,例如“ abc”,然后提交,您将被带到URL www.example.com/tabledata/abc