이전에 구현한 Flask 기반의 간단한 게시판 애플리케이션에 댓글 작성 및 표시 기능을 추가하는 방법을 안내해드리겠습니다.
댓글을 저장하기 위해 게시글 데이터 구조에 comments
필드를 추가합니다.
# 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>', methods=['GET', 'POST'])
def post_detail(post_id):
# post_id에 해당하는 게시글 찾기
post = next((post for post in posts if post['id'] == post_id), None)
if not post:
return "게시글을 찾을 수 없습니다.", 404
if request.method == 'POST':
author = request.form['author']
content = request.form['content']
new_comment = {'author': author, 'content': content}
post['comments'].append(new_comment)
return redirect(url_for('post_detail', post_id=post_id))
return render_template('post_detail.html', post=post)
@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,
'comments': [] # 댓글을 저장할 리스트 추가
}
posts.append(new_post)
post_id += 1
return redirect(url_for('index'))
return render_template('create_post.html')
if __name__ == '__main__':
app.run(debug=True)
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>
<hr>
<h3>댓글</h3>
<ul>
{% for comment in post.comments %}
<li><strong>{{ comment.author }}</strong>: {{ comment.content }}</li>
{% else %}
<li>댓글이 없습니다.</li>
{% endfor %}
</ul>
<hr>
<h3>댓글 작성</h3>
<form method="POST" action="{{ url_for('post_detail', post_id=post.id) }}">
<label for="author">작성자:</label>
<input type="text" id="author" name="author" required>
<br>
<label for="content">내용:</label>
<textarea id="content" name="content" required></textarea>
<br>
<button type="submit">댓글 달기</button>
</form>
<a href="{{ url_for('index') }}">목록으로 돌아가기</a>
{% endblock %}
-
서버를 실행합니다:
python app.py
-
웹 브라우저에서
http://127.0.0.1:5000/
로 접속하여 게시글을 작성하고, 각 게시글의 상세 페이지에서 댓글을 작성하고 확인할 수 있습니다.
이러한 수정으로 각 게시글에 댓글을 작성하고 표시하는 기능을 구현할 수 있습니다. 이제 사용자는 게시글에 대한 의견을 댓글로 남길 수 있으며, 각 게시글의 상세 페이지에서 댓글 목록을 확인할 수 있습니다.