본문 바로가기
Django

04. 홈페이지 기능 구현 - Read

by ㅣlㅣl 2024. 2. 15.

본 포스팅은 생활코딩 이고잉님의 강의 'Python Django Web Framework', Django Documentation을 토대로 작성된 포스팅입니다.


아무리 복잡한 웹페이지라도 결국 4가지 작업으로 귀결된다.

  • Create
  • Read
  • Update
  • Delete

기능을 하나씩 구현해보며 django 기초를 다져보자!

 

Read

우선 맨 처음 우리를 반겨주는 화면인 index를 꾸며주자.

기본적인 html 골격을 만들어 HttpResponse로 감싸주면 된다.

html 태그 & 문법에 관련해서는 나중에 따로 정리해보겠다!

 

# myapp > views.py
from django.shortcuts import render, HttpResponse
import random

# Create your views here.
# 첫 번째 파라미터 인자로 요청과 관련된 여러 정보가 있는 객체를 전달해주어야 함 (=관습적으로 request를 쓴다)
def index(request):
    return HttpResponse('''
    <html>
    <body>
    <h1>Django</h1>
    <ol>
        <li>routing</li>
        <li>view</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) # id 가변인자를 추가해보자!

 

초기 화면

 

 

 

본격적으로 웹사이트 게시판을 만들기 위해 아래 요소들을 추가해보자.

1. index에 존재하는 각 리스트 요소를 하나의 게시글로 만들어서 링크 달아주기

2. 게시글 링크를 클릭하면 게시글 제목을 띄워주고, 제목 아래 게시글의 내용을 표시해주기

 

  • 각 게시글을 dictionary 형태로 표현하고, 반복문을 이용하여 게시물마다 url 링크를 만들어주기
# myapp/views.py
from django.shortcuts import render, HttpResponse

# Create your views here.
# 첫 번째 파라미터 인자로 요청과 관련된 여러 정보가 있는 객체를 전달해주어야 함 (=관습적으로 request를 쓴다)
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):
    # 위에서 지정한 dictionary list를 전역변수로 지정
    global topics
    ol = ''

    # topics를 가지고 아래 html에서 지정한 list와의 링크를 만들어주기
    for topic in topics:
        ol += f'<li><a href="/read/{topic["id"]}">{topic["title"]}</a></li>'
    
    # 앞에서 for문으로 추가한 ol에 의해 리스트 만들어짐
    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) # id 가변인자를 추가해보자!

 

  • 상세보기 페이지 구현 - html 코드 함수화
    모든 게시물마다 동일한 html 코드를 복붙하면 당연히 보기 안좋을 것이다!
    따라서 HTMLTemplate() 이라는 함수를 통해 따로 빼주도록 한다.

# myapp/views.py
from django.shortcuts import render, HttpResponse

# Create your views here.
# 첫 번째 파라미터 인자로 요청과 관련된 여러 정보가 있는 객체를 전달해주어야 함 (=관습적으로 request를 쓴다)
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):
     # 위에서 지정한 dictionary list를 전역변수로 지정
    global topics
    ol = ''

    # topics를 가지고 아래 html에서 지정한 list와의 링크를 만들어주기
    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 create(request):
    return HttpResponse('Create')

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

 

 

index 페이지에서 링크를 클릭할 때마다 url과 출력 텍스트 내용이 바뀌는 것을 볼 수 있다.

Read - 1

 

Read - 2

 

요약 및 정리

  • 클라이언트에게 보내는 return 값에 가변인자를 추가할 수 있다
  • 반복되는 html 코드는 template 형태로 따로 꺼내면 코드가 훨씬 간결해진다

 


참고 자료

https://youtu.be/pbKhn2ten9I?si=NtCIfKXs9RozEzaQ

https://opentutorials.org/course/4886/31111

https://docs.djangoproject.com/ko/5.0/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 

'Django' 카테고리의 다른 글

03. App 만들기 (2)  (1) 2024.02.15
02. App 만들기 (1)  (0) 2024.02.15
01. Django 설치, Django project의 구성 요소들  (0) 2024.02.15