Django로 url을 정의하고 views.py에서 해당하는 method를 실행시키면 return 값에 따라 원하는 페이지를 보여줄 수 있다.
그런데 detailpage(상세페이지) 같은 경우, mainpage에서 선택한 해당 detailpage가 보여져야 하기 때문에 특정한 url과 특정한 content가 보여지는 detailpage 이어야 한다. 이를 구현하기 위해 아래와 같은 방법을 생각 해 볼 수 있다.
mainpage에서 여러 개의 list가 보여지는 상황이라면, 아래의 코드와 같이 'todo'라는 variable 안에 해당 list의 data 값이 있다. 여기서 todos는 views.py에서 GET method로 DB에서 해당 data를 불러온 것이다.
<body>
<h1>Todo의 Index 입니다</h1>
<a href="/todo/create">
<button>Write New Todo List</button>
</a>
<ul>
{% for todo in todos %}
<a href="/todo/{{ todo.id }}">
<li>{{ todo.content }}</li>
</a>
{% endfor %}
</ul>
</body>
todo에는 id, contents 등 models.py에서 선언한 attribute에 해당하는 data를 담고 있다.
따라서, todo.id 값으로 하나의 list를 특정 할 수 있다.
이렇게 선택된 한 개의 list의 id 값은 href 주소 값을 채우고 urls.py에서 정의해 준 방향으로 간다.
path('<int:todo_id>/', views.read)
이제 views.py의 read method가 실행된다.
def read(request, todo_id):
todo = Todo.objects.get(id=todo_id)
context = {
'todo': todo,
}
return render(request, 'todo/detail.html', context)
read method로 todo_id 값이 넘어오고, DB에서 해당하는 id 값의 data를 context variable에 담아서 detail.html로 보내준다.
<div>
<h1>{{ todo.content }}</h1>
<p>{{ todo.created_at }}</p>
<p>{{ todo.updated_at }}</p>
</div>
위와 같이 context로 data를 받은 detail.html은 {{todo.content}}를 통해 DB에 저장되 있던 특정한 content(data) 값을 client에게 보여줄 수가 있다.
이렇게 detailpage가 완성된다.
좀 복잡해 보이지만 이 흐름을 잘 따라가 보면 어떻게 detailpage를 만들 수 있는지 이해할 수 있을 것이다.
특히 html file에서 python을 사용할 수 있는 부분이 좀 재밌는 부분인 것 같다.
'Computer Programming > AI' 카테고리의 다른 글
TIL_Django Project에서 related_name이란 (1) | 2023.09.08 |
---|---|
Django Project에서 render와 redirect의 차이점 (0) | 2023.09.07 |
TIL_Django Project에서 ORM(Object Relational Mapping) (0) | 2023.09.05 |
TIL_Django Project 중 Cookie와 Session 정리 (1) | 2023.09.04 |
WIL_네 번째 주 (0) | 2023.09.03 |