-
장고 읽기 구현 2백엔드 : 서버공부/Django 2023. 7. 29. 13:03728x90
장고 읽기 구현 2
이제 read함수 부분을 구현해보겠습니다.
read함수도 똑같은 형식의 html형식을 공유합니다. 그렇기 때문에 html코드를 함수화 시켜보겠습니다.
아래와같이 코드를 수정해 보겠습니다.
from django.shortcuts import render, HttpResponse topics = [ {'id':1, 'title':'routing','body':'Routing is ..'}, {'id':2, 'title':'view','body':'View is ..'}, {'id':3, 'title':'Model','body':'Model is ..'} ] def HTMLTemplate(): global topics ol = '' for topic in topics: ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>' return f''' <html> <body> <h1>Django</h1> <ol> {ol} </ol> <h2>Welcome</h2> Hello, Django </body> </html> ''' def index(request): return HttpResponse(HTMLTemplate()) def read(request, id): return HttpResponse('Read!'+id) def create(request): return HttpResponse('Create')
이후 페이지를 로드해보면 화면은 이전과 같이 나오지만 재활용을 위한 기틀을 마련했습니다.
이제 index와 read를 구현하기위해
<h2>Welcome</h2> Hello, Django
위 코드부분을 변수화 시키겠습니다.
HTMLTemplate를 다음과 같이 수정해줍니다.
def HTMLTemplate(articleTag): global topics ol = '' for topic in topics: ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>' return f''' <html> <body> <h1>Django</h1> <ol> {ol} </ol> {articleTag} </body> </html> '''
index함수도 아래와 같이 작성해줍니다.
def index(request) : article = ''' <h2>Welcome</h2> Hello, Django ''' return HttpResponse(HTMLTemplate(article))
article을 HTMLTemplate의 인자로 전달하면 HTMLTemplate의 첫번째 파라메터가 받습니다.
위와같이 구성하면 로드되는 화면구성은 이전과 똑같지만 HTMLTemplate은 재사용가능한 부품이 되었다고 볼 수 있습니다.
이제 read함수도 작성해 보겠습니다.
def read(request, id): global topics article = '' for topic in topics: if topic['id'] == int(id): article=f'<h2>{topic["title"]}</h2>{topic["body"]}' return HttpResponse(HTMLTemplate(article))
for문과 if문을 사용해 topic['id'] == int(id)라면 제목은 topic의 title로 하고 본문은 topic의 body를 사용하도록 합니다.
그렇게 만들어진 결과를HttpResponse에 공급해줍니다.
아래는 수정사항을 반영한 전체코드입니다.
from django.shortcuts import render, HttpResponse topics = [ {'id':1, 'title':'routing','body':'Routing is ..'}, {'id':2, 'title':'view','body':'View is ..'}, {'id':3, 'title':'Model','body':'Model is ..'} ] def HTMLTemplate(articleTag): global topics ol = '' for topic in topics: ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>' return f''' <html> <body> <h1>Django</h1> <ol> {ol} </ol> {articleTag} </body> </html> ''' def index(request) : article = ''' <h2>Welcome</h2> Hello, Django ''' return HttpResponse(HTMLTemplate(article)) def read(request, id): global topics article = '' for topic in topics: if topic['id'] == int(id): article=f'<h2>{topic["title"]}</h2>{topic["body"]}' return HttpResponse(HTMLTemplate(article)) def create(request): return HttpResponse('Create')
아래는 최초화면입니다.
아래는 각 인덱스를 누르면 나타나는 화면들입니다.
읽기 구현을 통해 알 수 있는 장고의 장점
위와 같은 코드들은 장고의 혁명적인 점을 잘 보여주는 코드입니다.
우리가 갖고있는 문서가 1억개라고 가정해 봅시다. 이때 누군가 각 문서를 순서가 없는 리스트인 ul태그로 바꾸라고 한다면, 1억개를 수정하는것이아니라
아래와 같이 태그 하나만 수정해주면 됩니다.
def HTMLTemplate(articleTag): global topics ol = '' for topic in topics: ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>' return f''' <html> <body> <h1>Django</h1> <ul> {ol} </ul> {articleTag} </body> </html> '''
이렇게 되면 1억개의 문서가 모두 ul로 바뀌는 혁명적인 효과를 얻을 수 있습니다.
마지막으로 페이지 내부에서 Django부분을 클릭시에 홈으로 이동하여 페이지의 Flow를 개선해 보겠습니다.
def HTMLTemplate(articleTag): global topics ol = '' for topic in topics: ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>' return f''' <html> <body> <h1><a href="/myapp">Django</a></h1> <ol> {ol} </ol> {articleTag} </body> </html> '''
<h1><a href="/myapp">Django</a></h1>이 코드를 통해 Django에 링크를 걸어 홈으로 이동하도록 하였습니다.
'백엔드 : 서버공부 > Django' 카테고리의 다른 글
장고 생성 기능 구현 2 (0) 2023.07.29 장고 생성 기능 구현 1 (0) 2023.07.29 장고 읽기 구현 1 (0) 2023.07.29 장고를 사용하는 이유 (0) 2023.07.29 장고 라우팅 (0) 2023.07.29