Skip to content

Latest commit

 

History

History
166 lines (122 loc) · 5.13 KB

3-1.board_crud.md

File metadata and controls

166 lines (122 loc) · 5.13 KB

게시글 수정 및 삭제(CRUD) 기능 구현

이전에 구현한 Flask 기반의 간단한 게시판 애플리케이션에 게시글 수정 및 삭제(CRUD) 기능을 추가하자!

1. 게시글 수정 기능 구현

게시글을 수정하기 위해 다음과 같은 단계를 진행합니다:

  1. 수정 버튼 추가: 게시글 상세 페이지에 수정 버튼을 추가합니다.
  2. 수정 폼 생성: 기존 내용을 불러와 수정할 수 있는 폼을 생성합니다.
  3. 수정 처리 로직 구현: 수정된 내용을 저장하고 업데이트합니다.

1.1 수정 버튼 추가

post_detail.html 템플릿에 수정 버튼을 추가합니다:

<!-- templates/post_detail.html -->
{% extends 'base.html' %}

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<a href="{{ url_for('edit_post', post_id=post.id) }}">수정하기</a>
<a href="{{ url_for('delete_post', post_id=post.id) }}">삭제하기</a>
<a href="{{ url_for('index') }}">목록으로 돌아가기</a>
{% endblock %}

1.2 수정 폼 생성

edit_post.html 템플릿을 생성하여 수정 폼을 작성합니다:

<!-- templates/edit_post.html -->
{% extends 'base.html' %}

{% block title %}게시글 수정{% endblock %}

{% block content %}
<h2>게시글 수정</h2>
<form method="POST" action="{{ url_for('edit_post', post_id=post.id) }}">
    <label for="title">제목:</label>
    <input type="text" id="title" name="title" value="{{ post.title }}" required>
    <br>
    <label for="content">내용:</label>
    <textarea id="content" name="content" required>{{ post.content }}</textarea>
    <br>
    <button type="submit">수정하기</button>
</form>
{% endblock %}

1.3 수정 처리 로직 구현

app.py에 게시글 수정을 처리하는 라우트를 추가합니다:

# app.py

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# 임시 게시글 저장용 리스트
posts = []
post_id = 1

@app.route('/')
def index():
    return render_template('index.html', posts=posts)

@app.route('/post/<int:post_id>')
def post_detail(post_id):
    post = next((post for post in posts if post['id'] == post_id), None)
    if post:
        return render_template('post_detail.html', post=post)
    else:
        return "게시글을 찾을 수 없습니다.", 404

@app.route('/create', methods=['GET', 'POST'])
def create_post():
    global post_id
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        new_post = {
            'id': post_id,
            'title': title,
            'content': content
        }
        posts.append(new_post)
        post_id += 1
        return redirect(url_for('index'))
    return render_template('create_post.html')

@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
def edit_post(post_id):
    post = next((post for post in posts if post['id'] == post_id), None)
    if not post:
        return "게시글을 찾을 수 없습니다.", 404

    if request.method == 'POST':
        post['title'] = request.form['title']
        post['content'] = request.form['content']
        return redirect(url_for('post_detail', post_id=post_id))

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

if __name__ == '__main__':
    app.run(debug=True)

2. 게시글 삭제 기능 구현

게시글을 삭제하기 위해 다음과 같은 단계를 진행합니다:

  1. 삭제 버튼 추가: 게시글 상세 페이지에 삭제 버튼을 추가합니다.
  2. 삭제 처리 로직 구현: 삭제 요청을 받아 게시글을 삭제합니다.

2.1 삭제 버튼 추가

이미 앞서 post_detail.html에 삭제 버튼을 추가하였습니다.

2.2 삭제 처리 로직 구현

app.py에 게시글 삭제를 처리하는 라우트를 추가합니다:

# app.py

@app.route('/delete/<int:post_id>', methods=['POST'])
def delete_post(post_id):
    global posts
    post = next((post for post in posts if post['id'] == post_id), None)
    if not post:
        return "게시글을 찾을 수 없습니다.", 404

    posts = [post for post in posts if post['id'] != post_id]
    return redirect(url_for('index'))

삭제 요청은 보통 POST 메서드를 사용하여 처리합니다. 따라서 삭제 버튼을 폼으로 감싸고, POST 메서드로 요청을 보내도록 수정합니다:

<!-- templates/post_detail.html -->
{% extends 'base.html' %}

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<a href="{{ url_for('edit_post', post_id=post.id) }}">수정하기</a>
<form action="{{ url_for('delete_post', post_id=post.id) }}" method="POST" style="display:inline;">
    <button type="submit">삭제하기</button>
</form>
<a href="{{ url_for('index') }}">목록으로 돌아가기</a>
{% endblock %}

이러한 수정으로 게시글의 수정 및 삭제 기능을 구현할 수 있습니다. 이제 사용자는 게시글을 작성, 수정, 삭제할 수 있으며, 각 기능은 해당하는 라우트와 템플릿을 통해 처리됩니다.