2월 17, 2024

[Django] diary 만들어보기 (4) CRUD 구현-Read

https://www.programmingstory.com/2024/02/django-diary-3-crud-create.html

포스팅이 계속해서 이어지고 있다. 저번 포스팅에서는 CRUD 중에서 Create를 알아보았고 이번에는 CRUD 중에서 Read를 알아보려고 한다. 


Read를 하는 과정을 생각해보면, 

먼저 일기를 클릭하면 post/일기아이디/ url로 이동하여서 일기 페이지를 보여주어야 할 것이다. 그러기 위해서 먼저 urls.py부터 추가를 해보자. 


from django.urls import path
from diary import views

app_name='diary'
urlpatterns = [
    path('', views.index, name='index'),
    path('create/', views.create, name='create'), 
    path('<int:id>/', views.show, name='show'), # add this line
]


하지만 여기까지 썼다면 당연히 에러가 날 것이다. 왜냐하면 우리는 아직 views.show 함수를 만들지 않았기 때문이다. 그러면 이제 views.show를 만들러 views.py에 가보자

 

show 함수는 해당 아이디에 해당되는 일기를 보여주어야 하기 때문에 parameter로 추가적으로 id 값을 함께 가지게 된다.


def show(request, id):
    post = Post.objects.get(id=id)
    return render(request, 'diary/show.html', {'post':post})


이러면 show 함수는 diary/show.html로 render된다는 것을 알 수 있다. 그러면 순서대로 따라가, 우리는 show.html을 다시 만들어주어야 한다. 하던대로 이를 templates/diary/폴더 안에다가 생성해준다. 

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My diary</title>
  </head>
  <body>
    <div>
      <a href="{% url 'diary:index' %}">return</a>
      <h1>Title: {{ post.title }}</h1>
      <h3>Satisfaction: {{ post.satisfaction }}</h3>
      <p>Content: {{ post.content }}</p>
    </div>
  </body>
</html>


가장 위에는 홈 화면으로 돌아갈 수 있게 index url로 연결시켜줄 수 있는 return 버튼을 만들어주었고 그 다음에는 받은 post 객체에 대해 title, satisfaction, content 정보를 각각 출력할 수 있도록 코드를 작성했다. 

 

이런 식으로 한다면 

Title을 클릭하면 


이런식으로 Title, satisfaction, content가 보이는 페이지로 이동하고 위의 return을 누르면 다시 메인 화면으로 돌아오게 된다. 

 

다음 포스팅에서는 CRUD의 update를 다루어보도록 하겠다.