제네릭 뷰 DetailView

Ethan·2024년 1월 19일
0

Dear

목록 보기
10/13

장고의 DetailView 제네릭 뷰를 상속받는 상속 페이지를 구현하는 방법을 알아본다.


1. DetailView를 상속받는 클래스형 뷰 생성


1.1 기존 함수형 뷰 post_detail

기존에 작성된 함수형 뷰 post_detail은 아래와 같다. 주석처리 해준다.

#views.py

# def post_detail(request, post_id):
#     post = get_object_or_404(Post, id=post_id)
#     context = {"post": post}
#     return render(request, 'posts/post_detail.html', context=context)

1.2 변경된 클래스형 뷰 PostDetailView

DetailView를 상속받는 클래스형 뷰를 생성한다.

#views.py > PostDetailView

class PostDetailView(DetailView):
    model = Post
    template_name = "posts/post_detail.html"
    pk_url_kwarg = "post_id"
    context_object_name = "post"

접근할 모델을 정의하고, 렌더할 템플릿을 정의하고, url로부터 전달받는 인자를 정의하고, 데이터에 접근하기 위해 사용될 이름을 정의한다.

마찬가지로 context_object_name 변수에 지정한 을 이용해 템플릿에서 해당 을 통해 데이터에 접근할 수 있다.

또한 DetailView를 상속받기 위해서는 해당 클래스를 불러와야 한다.


1.3 url 패턴 변경

url 패턴에서 post_detail을 PostDetailView로 변경해야 한다.

#urls.py

urlpatterns = [
    # path('', views.index),
    path('', views.PostListView.as_view(), name="post-list"),
    path('posts/new/', views.PostCreateView.as_view(), name="post-create"),
    path('posts/<int:post_id>/', views.PostDetailView.as_view(), name="post-detail"),
    path('posts/<int:post_id>/edit/', views.post_update, name="post-update"),
    path('posts/<int:post_id>/delete/', views.post_delete, name="post-delete"),
]
profile
글로 쓰면 머리 속에 정리가 되...나?

0개의 댓글

관련 채용 정보