【问题标题】:Get HTML table row data to Flask function获取 HTML 表格行数据到 Flask 函数
【发布时间】:2021-01-06 10:32:47
【问题描述】:

我在下面的模板中有一个包含几列的 HTML 表格。表格的最后一列有一个按钮。代码如下。

index.html

<table id="deployment_table" class="table table-striped">
   <thead>
      <tr>
         {% for col in colnames %}
         <th>{{ col }}</th>
         {% endfor %}
      </tr>
   </thead>
   <tbody>
      {% for record in records %}
      <tr>
         {% for col in colnames %}
         <td>{{ record[col] }}</td>
         {% endfor %}
         <td class="td-actions text-right">
            <a href=ct_edit ><input type="submit" name="edit_btn" value="update"rel="tooltip" class="btn btn-info"></a>
            </input>
         </td>
      </tr>
      {% endfor %}
   </tbody>
</table>

当用户单击特定行的按钮时,我需要将所选行的第一列的值传递给 Flask 函数并使用此数据加载另一个 HTML 页面。

下面是flask后端函数。

@app.route('/ct_edit')
def ct_edit():
    print('ct_edit')
    # the value of the first column of the selected row => ID
    # do something with the ID value and get a result
    return render_template('ct_edit.html', result=result) 

到目前为止,我无法完成这项工作。对此我有什么建议吗?

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    首先,请注意,您的输入标签会关闭锚标签,而它应该是相反的,不确定它是否会影响本示例中的代码,但最好保持它们的顺序。

    第二件事,Flask 有一个名为 url_for 的东西,它可以帮助您利用 Jinja 模板,而不是硬编码 html 的页面名称,您可以引用各个函数的名称并传递特定的变量(您如下所示执行此操作 - 在您有引用或操作的地方,您在 href = "{{ url_for("name of the function") }}"

    在此示例中,由于您想要获取特定记录 - 为每条记录指定一个特定值。我放置了 row["id"],它指的是表中此记录的特定唯一值(我假设您有一些列对每一行都有唯一值 - 这应该放在 url_for 中) .

    然后在 Flask 函数 ct_edit 中,它负责显示您通过单击锚标记选择的特定行,应该接收该唯一值作为参数(也将其放在路由中,以便记录将是可区分的)。

    <a href="{{ url_for("ct_edit", record_id = row["id"]) }}"><input type="submit" name="edit_btn" value="update"rel="tooltip" class="btn btn-info">
            <i class="material-icons"></i></input></a>
    
    @app.route('/ct_edit/<int:record_id>')
    def ct_edit(record_id):
        print('ct_edit')
        # the value of the first column of the selected row => ID
        # do something with the ID value and get a result
        return render_template('ct_edit.html', result=result) 
    

    我希望我能为你带来一点启发。

    保持健康:)

    【讨论】:

    • 确实如此。非常感谢您的回答和同时展示实现这一目标的优雅方式!保持良好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2014-08-13
    • 2016-04-24
    相关资源
    最近更新 更多