Python Django Web Framework - 7/14. 홈페이지 읽기 기능 구현하기

leecw4u·2023년 10월 17일
0

Django

목록 보기
7/15
post-thumbnail

아무리 복잡한 어플도 네가지 안에 갖혀있다.
CRUD(Create, Read, Update, Delete)

이번에 해 볼 것은 Read이다.
Read는 homepage 와 상세보기로 나뉘는데 (뭔 말이지?)

일단, 기본적인 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 index(request):
    global topics
    ol = ''
    
    for topic in topics:
        ol += f'<li>{topic["title"]}</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)

topics에 리스트로 딕셔너리들을 묶어주고 for문으로 ol태그 안에 li 태그로 추가해준다.
이렇게 되면 일반 리스트 형태로 title이 정렬되는데 이걸 링크로 만들어주자

...
for topic in topics:
	ol += f'<li><a href="/read/{topic["id"]}">{topic["title"]}</a></li>'
return HttpResponse(f'''
...

이렇게 a태그 안에 href를 쓰게 되면
view.py안에 read 함수로 이동하게 되는 링크를 생성하게 된다.

def read(request, id):
    return HttpResponse('read!'+id)
profile
초보 개발자의 끄적끄적 스터디 블로그

0개의 댓글

관련 채용 정보