티스토리 뷰

Intro

현재 localhost에 접속하면 다음과 같이 post_list가 views.py에 구성되어있다.

다음으로 post제목을 클릭하면 detail_view 페이지로 이동할 수 있도록 구현해보자.

 

1. views.py에 post_detail 함수를 추가한다.

--post/views.py

from django.shortcuts import render
from post.models import Post

# Create your views here.

def post_list(request):
    posts = Post.objects.all()
    context = {'posts':posts}
    # posts = Post.Objects.filter(pub_date)
    return render(request, 'post_list.html', context)

def post_detail(request, pk):
    post = Post.objects.get(pk=pk)
    context = {'post':post}
    return render(request, 'post_detail.html', context)

여기서 pk는 primary key의 약자로 DB post_post Table의 id에 해당한다.

 

2. urls.py에 post_detail 경로를 추가한다.

--jblog/urls.py

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

from post.views import post_list, post_detail

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', post_list, name='post_list'),
    path('post/<int:pk>/', post_detail, name='post_detail'),
]

 

3. templates 폴더에 post_deail.html을 추가한다.

--post/templates/post_detail.html

<!DOCTYPE html>
<html>
 <head>
  <title>post_list</title>
 </head>

 <body>
  <h2> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </h2>
  <h1> ~ Welcome to visit jinozblog2019 ~ </h1>
  <h2> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </h2>

  <div>
   <h2>post제목 : <a href="">{{ post.title }}</a></h2>
   <h3>post내용 : {{ post.text }}</h3>
   <h4>post작성자/발행일 : {{ post.author }} / {{ post.pub_date }}</h4>
   <h5>-------------------------------------</h5>
  </div>
 </body>
</html>

<head> 부분의 <title>은 browser 탭에 표시되는 부분이다.

<body> ~Welcome to visit jinozblog~는 post_list의 제목을 클릭 후 post_detail로 전환 시 layout 유지 형태를 유지하기 위해 추가한 부분이고 나중에 templates/base.html을 구성하여 post_list view와 post_detail view 전환 시 템플릿 테그로 중복을 방지 적용한다.

4. 마지막으로 post_list.html에서 제목 클릭 시 post_detail.html로 이동하기 위해 링크를 걸어준다.

--post/templates/post_list.html 
<!DOCTYPE html>
<html>
 <head>
  <title>jinozblog2019</title>
 </head>

 <body>
  <h2> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </h2>
  <h1> ~ Welcome to visit jinozblog2019 ~ </h1>
  <h2> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </h2>
  {% for post in posts %}
  <div>
   <h2>post제목 : <a href="post/{{ post.pk }}">{{ post.title }}</a></h2>
   <h3>post내용 : {{ post.text }}</h3>
   <h4>post작성자/발행일 : {{ post.author }} / {{ post.pub_date }}</h4>
   <h5>-------------------------------------</h5>
  </div>
  {% endfor %}
 </body>
</html>

 

post제목의 <a href=""> 부분에 {% url 'post_detail' pk=post.pk %} 템플릿 테그를 적용하면서 정상적으로 작동한다.

 

 

최종적으로 localhost에 접속하여 제대로 작동하는 지 확인해보자.

127.0.0.1:8000

 

다음은 post제목 : First Post - Test 링크 부분을 클릭하면 다음과 같이 post_detail로 이동하는 것을 확인할 수 있다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함