아무리 복잡한 어플도 네가지 안에 갖혀있다.
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)