🛴

08. cafedetails 페이지

[참고]
아래 명령어는 구름IDE에서 다시 접속하실 때마다 실행해 주셔야 하는 명령어 입니다.
root@goorm:/workspace/컨테이너명# cd mysite root@goorm:/workspace/컨테이너명/mysite# source myvenv/bin/activate (myvenv)root@goorm:/workspace/컨테이너명/mysite#
myvenv가 붙지 않은 상태에서 그동안 명령어를 치셨다면 지금이라도 컨테이너를 삭제해버리시고 처음부터 다시 하시길 권장해 드립니다. (myvenv)가 붙지 않은 환경, 붙은 환경은 완전히 다른 환경이기 때문입니다. 물론, 애러를 잡거나 폴더 몇 개 지우는 것으로도 끝날 수 있지만, 초급자일 때에는 반복학습도 중요할 뿐더러 에러를 잡는 것이 어려울 수 있으니까요.
 

cafedetails 페이지 만들기

이제 cafelist 페이지에서 카페를 눌렀을 때 나오는 상세 화면, cafedetails 페이지를 만들어 보도록 하겠습니다.
 
  • tutorialdjango/mysite/tutorialdjango/urls.py
from django.contrib import admin from django.urls import path from main.views import index, cafelist, cafedetails urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('cafelist/', cafelist), path('cafelist/<int:pk>/', cafedetails), ]
 
  • tutorialdjango/mysite/main/views.py
from django.shortcuts import render from .models import Cafe def index(request): return render(request, 'main/index.html') def cafelist(request): cafes = Cafe.objects.all() context = { 'cafes':cafes } return render(request, 'main/cafelist.html', context) def cafedetails(request, pk): cafe = Cafe.objects.get(pk=pk) context = { 'cafe': cafe, } return render(request, 'main/cafedetails.html', context)
 
이제 아래 화면처럼 main 안에 템플릿은 3개가 됩니다. 마지막 템플릿입니다.
notion imagenotion image
 
아래 URL 패턴처럼 cafelist/{post번호}를 입력하시면 아래 페이지처럼 출력이 됩니다.
URL : https://tutorialdjango-bcrpr.run.goorm.io/cafelist/1/
 
실행화면실행화면
실행화면
 
간단하게 cafelist화면에서 cafe 제목과 내용을 클릭하였을 때 해당 cafedetails로 이동하도록 만들어 보도록 하겠습니다.
 
  • tutorialdjango/mysite/main/templates/main/cafelist.html
<!DOCTYPE html> <html> <head> <title>cafelist</title> </head> <body> <h1>cafelist</h1> <table> {% for cafe in cafes %} <tr onclick="location.href='/cafelist/{{ cafe.pk }}/'"> <td>{{ cafe.name }}</td> <td>{{ cafe.content }}</td> </tr> {% endfor %} </table> </body> </html>
 
연결된 화면입니다. 해당 post 제목과 내용을 클릭하면 해당 포스팅으로 이동합니다.
 
notion imagenotion image
 
notion imagenotion image
notion imagenotion image
 
이번에는 반대로 posting 상세 내용에서 목록으로 넘어가는 링크 만들어 보도록 하겠습니다.
 
  • 컨테이너명/mysite/main/templates/main/cafedetails.html
<!DOCTYPE html> <html> <head> <title>cafelist</title> </head> <body> <h1>cafedetails</h1> <p>{{cafe.name}}</p> <p>{{cafe.content}}</p> <a href="/cafelist/">목록</a> </body> </html>
 
자, 이제 좀 더 고급진 방법을 알아보도록 하겠습니다. 이해를 돕기 위해 이 부분은 개인의 습득 속도에 따라 선택적으로 반영하도록 하겠습니다. (따라하지 않으셔도 괜찮습니다.)
 
  1. urls.py 수정
    1. from django.contrib import admin from django.urls import path from main.views import index, cafelist, cafedetails urlpatterns = [ path('admin/',admin.site.urls), path('',index), path('cafelist/',cafelist), path('cafelist/<int:pk>/',cafedetails, name='cafedetails'), ]
       
  1. 각각의 html 파일 수정
    1. <!DOCTYPE html> <html> <head> <title>cafelist</title> </head> <body> <h1>cafelist</h1> <table> {% for cafe in cafes %} <tr onclick="{% url 'cafedetails' cafe.id %}"> <td>{{cafe.name}}</td> <td>{{cafe.content}}</td> <tr> {% endfor %} </body> </html>