글의 전체 목록에는 모든 내용을 표시할 수 없다. 각각의 글이 가진 모든 내용을 표시할 글 상세 페이지를 만들어보자.
페이지를 만들때마다 항상 하던 작업을 먼저 해주자
View
[blog/views.py]
def post_detail(request):
return render(request, "post-detail.html")
URLconf
[config/urls.py]
from blog.views import index, post_list, post_detail
urlpatterns = [
path('admin/', admin.site.urls),
path("", index),
path("posts/", post_list),
path("posts/1/", post_detail),
]
Template
[templates/post_detail.html]
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div id="navbar">
<span>woojinlog</span>
</div>
<div id="post-detail">
<h1>Post Detail</h1>
</div>
</body>
</html>
1. 동적인 URL 경로 만들기
각각의 글들에 대한 url들을 지정해줘야한다. 그러기 위해선 각 페이지들의 고유 이름들이 있어야 하는데 이것을 id 값으로 지정해주고 만들어보자
[config/urls.py]
urlpatterns = [
...
path("posts/<int:post_id/", post_detail),
]
[blog/views.py]
def post_detail(request, post_id):
post = Post.objects.get(id=post_id)
print(post)
context = {
"post":post,
}
return render(request, 'post_detail.html', context)
[templates/post_detail.html]
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div id="navbar"> # 글 가져오기
{% if post.thumbnail %}
<img src="{{ post.thumbnail.url }}">
{% endif %}
<span>{{ post.title }}</span>
</div>
<div id="post-detail">
<p>{{ post.content|linebreaksbr }}</p>
<ul class="comments"> # 댓글 목록
{% for comment in post.comment_set.all %}
<li class="comment">{{ comment.content }}</li>
{% empty %}
<li class="comment-empty">아직 댓글이 없습니다.</li>
{% endfor %}
</ul>
</div>
</body>
</html>
페이지를 만들었으면 글 목록에서 상세페이지로 바로 이동할 수 있는 연결 링크를 만들자
[templates/post_list.html]
...
{% for post in posts %}
<li class='post'>
<div>
<a href='/posts/{{ post.id }}/">{{ post.title }}</a>
</div>
...
위의 코드를 작성하면 글의 제목을 클릭하여 상세페이지로 이동할 수 있다!
다음시간엔 글과 댓글을 직접 작성할 수 있는 기능을 넣어볼 것이다..!!
'Python > Django' 카테고리의 다른 글
[Django] woojin's blog 프로젝트: 글/댓글 작성 (1) | 2023.06.27 |
---|---|
[Django] woojin's blog 프로젝트: 유저가 업로드하는 정적파일 (0) | 2023.06.16 |
[Django] woojin's blog 프로젝트: CSS와 정적파일 (0) | 2023.06.15 |
[Django] woojin's blog 프로젝트: 글과 댓글 보여주기 (0) | 2023.06.15 |
[Django] woojin's blog 프로젝트: 글과 댓글 모델 구현 (1) | 2023.06.14 |