HTML表单按钮不从sqlite数据库中删除行

时间:2017-06-01 04:59:01

标签: python html sqlite flask

我在pythonanywhere中使用python和html构建了一个论坛,用户可以在其中发布插入sqlite数据库的信息。在每个帖子的底部是一个删除按钮,它将从数据库中删除它所在的帖子并刷新页面。此时删除按钮仅在帖子保留时刷新页面。我想知道如何编辑代码,以便删除附加表单按钮的帖子,并刷新页面。

HTML Code snippet

{% for post in forumposts %}
<tr>
    <td>
    <h1>{{post[1]}}</h1>
    <h3>{{post[3]}}</h3>
    <p>{{post[2]}}</p>
    <p>{{post[6]}}</p>
    <img src="{{post[7]}}" alt="Wrong image link.">
    <p></p>
    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value="{{ postid }}"name=post_to_delete></input>
    <input type=submit></input>
    </form>
    </td>
</tr>
    {%endfor%}
</table>

Python代码段

@app.route('/delete', methods=['POST'])
def delete_post():
    db = connect_db()
    db.execute('DELETE FROM posts WHERE postid = ?', [request.form['post_to_delete']])
    db.commit()
    db.close()
    return redirect(url_for('forum'))

1 个答案:

答案 0 :(得分:0)

让代码正常工作。

HTML

{% for post in forumposts %}
<tr>
    <td>
    <h1>{{post[1]}}</h1>
    <h3>{{post[3]}}</h3>
    <p>{{post[2]}}</p>
    <p>{{post[6]}}</p>
    <img src="{{post[7]}}" alt="Wrong image link.">
    <p></p>
    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value={{post[0]}} name=post_to_delete></input>
    <input type=submit value=POST></input>
    </form>
    </td>
</tr>
    {%endfor%}
</table>

PYTHON

@app.route('/delete', methods=['POST'])
def delete_post():
    if request.method == 'POST':
        db = connect_db()
        db.execute('DELETE FROM posts WHERE postid = ?', (request.form['post_to_delete'],))
        db.commit()
        db.close()
        return redirect(url_for('forum'))

希望这有助于某人。 :)