HTML5/반응형 웹

시 업로드 페이지 만들기 (템플릿과 폼)

forSilver 2025. 7. 13. 14:37
반응형

 

📘 『시마당 프로젝트 따라하기』

6장. 시 업로드 페이지 만들기 (템플릿과 폼)

작성자: easyfly
작성일: 2025년 7월 13일


🟧 1. 앱 구조 개요

우리는 아래 3가지를 설정하게 됩니다:

파일 역할
forms.py 사용자가 입력하는 폼 정의
views.py 요청을 받고 응답하는 로직 처리
templates/poem/upload.html HTML 양식 페이지 작성

🟦 2. 폼 생성: forms.py

📁 위치

madang/poem/forms.py

📄 코드 작성

from django import forms
from .models import Poem

class PoemForm(forms.ModelForm):
    class Meta:
        model = Poem
        fields = ['title', 'content', 'author']

사용자가 작성할 항목은 제목, 내용, 작가입니다.


🟧 3. 뷰 함수 작성: views.py

📁 위치

madang/poem/views.py

📄 코드 추가

from django.shortcuts import render, redirect
from .forms import PoemForm

def upload_poem(request):
    if request.method == 'POST':
        form = PoemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('upload_success')
    else:
        form = PoemForm()
    return render(request, 'poem/upload.html', {'form': form})

def upload_success(request):
    return render(request, 'poem/success.html')


🟧 4. URL 연결

📁 위치

madang/poem/urls.py  ← 새로 생성

📄 코드 작성

from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_poem, name='upload_poem'),
    path('success/', views.upload_success, name='upload_success'),
]

그리고 simadang/urls.py에 연결:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('poem/', include('poem.urls')),
]

🟧 5. 템플릿 생성

📁 디렉터리 생성

mkdir -p poem/templates/poem

📄 upload.html 작성

<!DOCTYPE html>
<html>
<head>
    <title>시 업로드</title>
</head>
<body>
    <h1>시 업로드</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">제출</button>
    </form>
</body>
</html>

📄 success.html 작성

<!DOCTYPE html>
<html>
<head>
    <title>업로드 완료</title>
</head>
<body>
    <h1>시가 성공적으로 업로드되었습니다!</h1>
    <a href="/poem/upload/">다시 작성하기</a>
</body>
</html>

🧪 6. 확인

✅ 개발 서버 실행

python manage.py runserver 0:8000

✅ 접속 주소

http://<EC2 IP>:8000/poem/upload/


📝 정리

항목 완료 여부
폼 생성 (forms.py)
뷰 작성 (views.py)
URL 연결 (urls.py)
HTML 템플릿 작성
시 업로드 기능 구현

다음 예고 – 『7장. 업로드된 시 목록 보기 (ListView 만들기)』

  • 업로드된 시들을 한눈에 볼 수 있도록 목록 페이지를 구현합니다.
  • 이후 전자책 출간용 EPUB 변환으로 이어질 예정입니다.