본문 바로가기
Python/Django

Django get_object_or_404!

by K-밍키 2022. 6. 13.

# main.html
<a href="{% url 'detail' post.id %}">상세보기</a>

# urls.py

path('post/<int:post_id>', post.views.detail, name="detail")

# views.py

def detail(request, post_id):
	post_detail = get_object_or_404(Post, pk=post_id)
    return render(request, 'post/detail.html', {'post':post_detail})

1. main.html

 : main에서 상세페이지로 넘어갈 때 post.id를 같이 넘겨준다.

 

2. path-converter

 : post가 생성될 때마다 post_id를 path-converter로 하여 detail함수에 넘겨준다는 의미이다.

 

3. get_object_or_404

 : path-converter로부터 넘겨받은 post_id를 받아 primary key가 post_id인 객체가 있다면 가져오고 없다면 404에러를 반환하라는 의미이다.