Python Django Web Framework - 8/14. 읽기기능 상세보기 페이지 만들기

leecw4u·2023년 10월 24일
0

Django

목록 보기
8/15
post-thumbnail

저번 글에 이어서 read를 구현해 보자
Python Django Web Framework - 7/14.

Read쪽을 관찰해 보니 기본적인 html형식을 따른다.

따라서 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> 태그를 사용한다.

index 함수

HTMLTemplate을 사용하여 index 함수를 수정해보자

 def index(request):
    article = '''
        <h2>Welcome</h2>
        hello Django
    ''' 
    return HttpResponse(HTMLTemplate(article))

article 이란 변수를 만들어 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))
...

topic의 id가 request를 받았을 때 id랑 일치한다면
article에 id에 해당하는 body를 출력해주도록 한다.
⚠️ id 값이 str이므로 int로 변경해주도록 한다.

profile
초보 개발자의 끄적끄적 스터디 블로그

0개의 댓글

관련 채용 정보