2월 17, 2024

[Django] diary 만들어보기 (3) CRUD 구현-Create

https://www.programmingstory.com/2024/02/django-diary-2-mtv-models-templates-view.html

전 포스팅에서는 MTV 패턴의 기본적인 골격을 잡아보는 연습을 했다. 이제는 diary에서 새로운 일기를 추가하고, 수정하고, 삭제하고 보여주는 것을 구현해볼 것이다. 

흔히 우리는 이것을 CRUD라고 하는데 (Create, Read, Update, Delete)의 약자이다. 


먼저 Create 부터 구현을 해보자.

Create을 하기 위해서는 post/create/라는 url로 이동하면 새로운 화면이 보여야 하고, 그러기 위해서는 urls.py 함수에 views.create으로 이동할 수 있게 views 함수도 수정을 해주어야 한다. 

 

먼저 그럼 diary/urls.py에 들어가서 url 경로부터 추가를 해주자. 

from django.urls import path
from diary import views

urlpatterns = [
    path('', views.index, name='index'), 
    path('create/', views.create, name='create'), # add this line
]


그리고 urlpatterns에도 써있듯이, 두 번째 인자로 views.create라는 함수를 필요로 함으로 views.py에 가서 create 함수를 만들어주자. 아래의 코드처럼 작성해주면 된다. 

#views.py
def create(request):
    return render(request, 'diary/create.html')

 

create 함수는 create.html 페이지로 render해주기 때문에 create.html 페이지를 새롭게 만들 필요가 있다. 미리 만들어놓은 templates/diary 폴더에 create.html 파일을 하나 만들어주고 새 일기를 추가할 때 화면을 작성해주면 된다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <h1>new diary</h1>
    <form action="{% url 'diary:index' %}" method="POST">
      {% csrf_token %}
      <p>title</p>
      <input name="title" /> <br />
      <p>Satisfaction</p>
      <input name="satisfaction" /> <br />
      <p>content</p>
      <textarea name="content" rows="30" cols="40"></textarea> <br />
      <input type="submit" value="submit" />
    </form>
  </body>
</html>

create.html에서 create한 정보를 다시 diary의 index url로 넘겨주는 것이고 그 방식이 POST가 되는 것이다. 새롭게 추가할 경우에 필드 값인 title, satisfaction, content 값을 input으로 받을 수 있도록 해 주었다. 

 

그러면 이제 index 함수에서 들어오는 method가 POST이냐 GET이냐에 따라서 상황을 다르게 처리해주어야 한다. 

그러므로, views.py에서 def index를 아래와 같이 수정해준다.

def index(request):
    if request.method == 'GET': # index
        posts = Post.objects.all()
        return render(request, 'diary/index.html', {'posts': posts})
    elif request.method == 'POST': # create
        title = request.POST['title']
        satisfaction = request.POST['satisfaction']
        content = request.POST['content']
        Post.objects.create(title=title, satisfaction=satisfaction, content=content)
        return redirect('diary:index') 

즉, 그냥 목록을 보여줄 때와 새롭게 create을 통해 POST할 경우를 분리하는 것이다. 

 

또한, 

Create을 하기 위해서는 추가를 할 수 있는 버튼이 필요하다. 버튼을 누르면 새로운 일기를 추가할 수 있는 페이지로 넘어가야 하기 때문에 index.html에 아래와 같이 수정을 해준다. 

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>My diary</title>
  </head>
  <body>
    <h1>Diary page</h1>
    <a href="/post/create">add</a>
    {%for post in posts%}
    <div style="border: 2px solid green;">
      <a href="/post/{{post.id}}">
        <h3> {{post.title}} </h3>
      </a>
      <h3> satisfied: {{post.satisfaction}} </h3>
      <h3> {{post.content}} </h3>
    </div>
    {% endfor %}
  </body>
</html>

<body> 뒤에 add 라는 링크를 걸어 준 것 이외에는 전 포스팅에서 다루었던 코드와 동일하다. 

 

이렇게 해주고 확인해보면,

이런 식으로 add 버튼이 새롭게 생겼고, add를 클릭해보면


위와 같이 화면이 잘 나오는 것을 알 수 있다. 이렇게 하면 새 일기를 만들어 줄 수 있다.

 

이제 CRUD 중에서 C를 구현했으니 다음 포스팅에서는 R (read)에 대해서 알아보도록 하겠다.