127.0.0.1:8000/detail/1(id)
127.0.0.1:8000/detail/2(id)
127.0.0.1:8000/detail/3(id)
<a href="{% url 'detail' post.id %}">
<h3>{{ post.title }}</h3>
</a>
in urls.py
path('detail/<int:post_id>', views.detail, name='detail')
이때 url에 int 외에 str 형도 넘겨주는 것이 가능하다.
post_id
: detail 함수에 넘겨줄 것. 앞에 타입을 명시.
#잘못된 코드
def detail(request, post_id):
Post = post.objects.filter(id=post_id)
return render(request, 'detail.html', {'Post':Post})
objects.filter
내지는 objects.all()
는 쿼리셋 객체를 반환한다. 이 쿼리셋 객체는 html 내부에서 for문으로만 각각의 객체에 접근할 수 있기 때문에 예컨대 다음과 같이 접근하지 못한다.
<h3>{{ Post.title }}</h3>
<h4>{{ Post.body }}</h4>
즉 다음과 같이만 접근할 수 있는 것이다.
{% for post in Post %}
{{post.title}}
{% endfor %}
그런데 우리가 디테일 페이지에서 확인하고 싶은 것은 오직 Post 객체 하나이므로, 이때에는 get
또는 get_object_or_404
메소드를 사용한다.
post.ojbets.get(id=post_id)
get_object_or_404(post, pk=post_id)