将按钮按下与表格行关联 Flask/Python

4

我有一个index.html文件:

            {% for item in data %}
            <tr>
            <td>{{item[0]}}</td>
            <td>{{item[1]}}</td>
            <td>{{item[2]}}</td>
            <td>{{item[3]}}</td>
            <td>{{item[4]}}</td>
            <td>{{item[5]}}</td>
            <td>{{item[6]}}</td>
            <td>{{item[7]}}</td>
            <td>{{item[8]}}</td>
            <td>{{item[9]}}</td>
            <td>{{item[10]}}</td>
            <td>
                    <form action="{{ url_for('history') }}" method="POST">
                    <button type="submit"> History </button>
                    </form>
            </td>
            </tr>
            {% endfor %}

在app.py中:

@app.route('/history', methods=['GET', 'POST'])
def history():

    return render_template('history.html')

我的网页上有一个带有许多行的表格,每一行都有一个标着“历史记录”的按钮。由于现在每个按钮都执行相同的动作并指向history(),如何区分原始点击来自哪一行数据?


为什么不直接在表单中创建选择字段呢?使用表格时,你需要多次重复几乎相同的代码。表单是用来传递数据到服务器的,而表格只是用来以表格形式表示某些内容... - Dinko Pehar
2个回答

2

我写这篇答案是希望能够帮助到某些人。 检查每个表格行是否显示了一本书,并且在表格行末尾有一个编辑按钮。

           {% for book in books %}
            <tr>
                <td>{{ book[1] }}</td>
                <td>{{ book[2] }} </td>
                <td>{{ book[3] }} </td>
                <td>{{ book[4] }} </td>
                <input id="book_id" name="book_id"
                       type="hidden" value="{{ book[0] }}">
                <td><button type="submit" name="edit" value="{{ book[0] }}"
                            formmethod="post">Edit</button></td>
            </tr>

每一行都有一个隐藏的book_id,用于使用以下代码在后端检索书籍:
        if request.form.get("edit"):
        print('Book ID: ', request.form.get('edit'))

2

您需要将项目ID添加到HTML表单中,但不能显示它。https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input/hidden

可以这样做:

<form action="{{ url_for('history') }}" method="POST">
    <input id="historicalId" name="historicalId" type="hidden" value="{{item.id}}">
    <button type="submit"> History </button>
</form>

然后在Flask中,您需要解析请求表单体。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接