ビジネスパーソン・ガジェット置場 empty lot for business

営業や仕事、それに伴う生活を便利に楽にするツール、ガジェットを作ります。既にあるツールも自分用にカスタマイズ。

python: Flaskアプリの作成⑦ 記事の削除

備忘録です。

今回は投稿した記事を削除する方法についての備忘録です。

記事の削除

記事をデータベースから削除する

記事の削除は、ページを新たに作るわけではないのでapp.pyにroutingすれば大丈夫です。あとは、deleteボタンを表示したいページでそのdeleteへのリンクを設置すれば完了です。

 

その1 app.pyでdelete関数を作る

# app.py

# やりたいことを削除する
@app.route('/aspirations/delete/<int:id>')
def deleat_aspiration(id):
    # 渡されたidのデータを取得し変数に格納
    aspiration_to_delete = Aspiration.query.get_or_404(id)
    # 削除する
    db.session.delete(aspiration_to_delete)
    db.session.commit()
    # 削除後のデータを並べ替えて表示する
    aspirations = Aspiration.query.order_by(Aspiration.created_at)
    return render_template('aspirations.html', aspirations=aspirations)

 

その2 deleteボタンを設置したいページにリンクを貼る

# aspirations.html

{% extends "base.html"%}

{% block content %}
<a href="{{ url_for('add_aspiration')}}" class='btn btn-outline-primary float-end mt-2'>やりたいこと登録</a>
<h1 class="mt-4">やりたいこと一覧</h1>
{% for aspiration in aspirations %}
  <div class="shadow p-3 mb-5 bg-body rounded">
    <h2>{{ aspiration.title }}</h2>
    <small>作成日:{{ aspiration.created_at.strftime('%Y-%m-%d %H:%M') }}</small><br/>
    {% if aspiration.completed_at %}
      <small>完了日:{{ aspiration.completed_at.strftime('%Y-%m-%d')}}</small><br/>
    {% endif %}
    {{ aspiration.content }} <br/><br/>
    # 編集ページへのリンク
    <a href="{{ url_for('edit_aspiration', id=aspiration.id )}}" class="btn btn-outline-secondary btn-sm">編集</a>
    # 削除用のリンク
    <a href="{{ url_for('deleat_aspiration', id=aspiration.id)}}" class="btn btn-outline-danger btn-sm">削除</a>
  </div>
{% endfor %}
{% endblock %}

 

削除ボタン

上記、編集ボタンは編集ページへのリンク、削除ボタンは該当する記事を削除できます。