0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【第3回】登山&キャンプ記録アプリ開発|投稿の詳細表示・編集・削除機能を実装!

Posted at

【第3回】登山&キャンプ記録アプリ開発|投稿の詳細表示・編集・削除機能を実装!

こんにちは、Soraです!
前回は投稿機能や画像アップロードについて紹介しました。

今回は、投稿内容の「**詳細表示」「編集」「削除」**を実装したので、その内容をまとめていきます!


🔎 詳細ページでできること

  • タイトル・感想・日付・住所を表示
  • 複数枚の画像をスライド的に表示(予定)
  • Googleマップの埋め込み

🛠 編集・削除機能でできること

  • 投稿者だけが編集・削除可能
  • ログインしていないとアクセスできない(@login_required
  • 編集後は自動的に詳細ページにリダイレクト

💡 使用技術&ポイント

機能 技術 or 工夫
編集・削除制限 post.user_id != current_user.id
アクセス制御 @login_required
編集フォーム表示 既存データをフォームに渡す
削除確認 GET/POSTの両対応

🧩 実装コード(抜粋)

詳細ページ

@app.route('/post/<int:post_id>')
def post_detail(post_id):
    post = Post.query.get_or_404(post_id)
    return render_template('post_detail.html', post=post)

編集ページ

@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.user_id != current_user.id:
        abort(403)

    if request.method == 'POST':
        post.title = request.form['title']
        post.date = datetime.strptime(request.form['date'], "%Y-%m-%d").date()
        post.address = request.form['address']
        post.description = request.form['description']
        post.map_iframe = request.form.get('map_iframe')
        db.session.commit()
        return redirect(url_for('post_detail', post_id=post.id))

    return render_template('edit.html', post=post)

振り返り☑️

  • 他人の投稿を編集できてしまう → post.user_id != current_user.id で制御!
  • 非ログイン状態で編集URLを直打ち → @login_required でブロック!
  • 削除後のリダイレクト先に迷った → 一覧(home)に戻すのが自然!
  • 投稿毎のページを見られるようになってアプリ感UP!

次回予告ッ‼️

次回は”Flask-admin”の活用法を紹介予定です!

ソースコードはこちら💁

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?