Post에 템플릿 링크 만들기
blog/templates/blog/post_list.html
파일에 아래와 같이 링크를 추가한다.
x
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}
{% url 'post_detail' pk=post.pk %}
을 설명하면,
{% %}
는 장고 템플릿 태그를 말한다.post_detail
은blog.views.post_detail
의 뷰 경로이다.pk=post.pk
이란pk
는 데이터베이스의 각 레코드를 식별하는 기본키(Primary Key)의 줄임말인데, Post 모델에서 기본키를 지정하기 않았기 때문에 장고는pk
라는 필드를 추가해서 새로운 게시물이 추가될 때 마다 그 값이 1, 2, 3 등으로 증가하게 된다.post.pk
를 써서 기본키에 접근할 수 있고Post
객체 내 다른 필드에도 접근할 수 있다.
Post 상세 페이지 URL 만들기
blog/urls.py
파일에 URL을 만들어, 장고가 post_detail
뷰로 보내, 게시글이 보이게끔 아래와 같이 blog/urls.py
파일에 URL을 추가한다.
x
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
(?P<pk>\d+)
는 장고가 pk
변수에 모든 값을 넣어 뷰로 전송하겠다는 뜻이다. \d
는 문자를 제외한 숫자 0~9 중, 한 가지 숫자만 올 수 있다는 것을 의미한다. +
는 그 이상의 숫자가 올 수 있다는 뜻이다.
Post 상세 페이지 내 뷰 추가하기
blog/views.py
에 아래 코드를 추가하고 뷰를 하나 아래와 같이 작성한다.
from django.shortcuts import render, get_object_or_404
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
get_object_or_404
는 만약 pk
에 해당하는 Post
가 없을 경우에는 404 에러를 보여주고, 있을 경우에는 그 pk
에 해당하는 Post
를 post
변수에 저장하게 된다.
Post 상세 페이지 템플릿 만들기
blog/templates/blog
디렉토리 안에 post_detail.html
이라는 새 파일을 생성하고 아래와 같이 코드를 작성한다.
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
이제 서버를 실행시키고 블로그 게시글의 상세 페이지를 확인해본다.
배포
다시 한번 Gtihub로 업로드한다.
xxxxxxxxxx
$ git status
$ git add --all .
$ git status
$ git commit -m "Added view and template for detailed blog post as well as CSS for the site."
$ git push
그 다음 PythonAnywhere Bash Console을 열고 아래와 같이 입력하고 Web tab에서 Reload를 누른다.
xxxxxxxxxx
$ cd my-first-blog
$ git pull
[...]
'Python > Django' 카테고리의 다른 글
장고 걸즈 튜토리얼 따라하기 14 - 장고 폼 (0) | 2019.01.07 |
---|---|
장고 걸즈 튜토리얼 따라하기 12 - 템플릿 확장 (0) | 2019.01.04 |
장고 걸즈 튜토리얼 따라하기 11 - CSS (0) | 2019.01.03 |
장고 걸즈 튜토리얼 따라하기 10 - 장고 템플릿 (0) | 2019.01.02 |
장고 걸즈 튜토리얼 따라하기 9 - 템플릿 동적 데이터 (0) | 2018.12.27 |