저번 글에 이어서 read를 구현해 보자
Python Django Web Framework - 7/14.
Read쪽을 관찰해 보니 기본적인 html형식을 따른다.
...
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="/">Django</a></h1>
<ol>
{ol}
</ol>
{articleTag}
</body>
</html>
'''
...
이렇게 HTMLTemplate
함수를 만들게 된다면 재사용 가능한 부품이 된다.
Django를 눌렀을 때 홈으로 돌아와야 함으로 <a>
태그를 사용한다.
HTMLTemplate
을 사용하여 index 함수를 수정해보자
def index(request):
article = '''
<h2>Welcome</h2>
hello Django
'''
return HttpResponse(HTMLTemplate(article))
article
이란 변수를 만들어 HTMLTemplate
로 보내준다.
...
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))
...
topic의 id가 request를 받았을 때 id랑 일치한다면
article에 id에 해당하는 body를 출력해주도록 한다.
⚠️ id 값이 str이므로 int로 변경해주도록 한다.