본문 바로가기
파이썬/파이썬 장고

Django) 2편, 홈페이지 꾸미기(Views.py 가공하여 상세 사이트 들어가기), HTML Template

by SeH_ 2023. 1. 15.
반응형

모든 내용은 생활코딩 유튜브를 참고하였습니다. 

 

1. Views.py의 index를 가공해 보겠습니다.

from django.shortcuts import render,HttpResponse
import random
# Create your views here.
# 클라이언트로 정보를 전달할 함수

def index(request):
    return HttpResponse('''
    <html>
    <body>
        <h1>Django</h1>
        <ol>
            <li>routing</li>
            <li>views</li>
            <li>model</li>
        </ol>
        <h2>Welcome</h2>
        Hello,Django

    </body>
    </html>
    ''')

def create(request):
    return HttpResponse('Create!')
def read(request,id):
    return HttpResponse('read!' +id)

Index 함수는 Home view를 바꾸는 거였죠?

urls.py에서 그렇게 설정했습니다.

 

그럼 이렇게 Home 화면이 바뀌게 됩니다. 

 

2. 파이썬 답게 for문을 통해 <li> 태그를 재가공합니다.

이 과정에서 1. routing, 2. views, 3. model을 클릭하면 해당 상세페이지 주소로 이동하는 <a href> 태그를 지정합니다.

이 href 태그 주소들이 다 read 주소를 불러오는 홈페이지로 지정하였습니다.

 

from django.shortcuts import render,HttpResponse
import random
# Create your views here.
# 클라이언트로 정보를 전달할 함수
topics = [
{'id' : 1, 'title' :'routing', 'body' : 'Routing is...'},
{'id' : 2, 'title' :'view', 'body' : 'View is...'},
{'id' : 3, 'title' :'Model', 'body' : 'Model is...'},
]
def index(request):
    global topics
    ol = ''
    for topic in topics :
        ol += f'<li><a href ="/read/{topic["id"]}">{topic["title"]}</a></li>'

    return HttpResponse(f'''
    <html>
    <body>
        <h1>Django</h1>
        <ol>
            {ol}
        </ol>
        <h2>Welcome</h2>
        Hello,Django

    </body>
    </html>
    ''')

def create(request):
    return HttpResponse('Create!')
def read(request,id):
    return HttpResponse('read!' +id)

이렇게 되면, 모든 상세페이지는 read에 따라 달라지겠죠?

 

html을 계속 쓰는 과정도 힘드니, html 만드는 코드를 함수로 지정합니다.(Template화 시킵니다!)

 

3. HTML Template 함수를 지정합니다.

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>
    '''

<h1><a href = "/">Django</a></h1> 이 부분은 Django를 눌렀을 때 Home으로 가는 a 태그를 따로 설정하였습니다.

 

4. HTML template 함수를 이용하여 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))

 

댓글