[Python Django] 3-4. CBV ListView를 이용한 List 구현

2022. 3. 26. 09:40Python/Django Framework

반응형

views.py 수정

  • BoardListView 클래스 추가
# board/views.py

class BoardListView(ListView):
    template_name = "board_list.html"
    model = Board
    context_object_name = "board_list"
    ordering = "-id"

urls.py 수정

# board/views.py

from django.urls import path

from board.views import BoardCreateView, BoardDetailView, BoardListView

urlpatterns = [
    path('create/', BoardCreateView.as_view()),
    path('list/', BoardListView.as_view()),
    path('detail/<int:pk>/', BoardDetailView.as_view())
]

board_list.html 템플릿 추가

# board/templates/board_list.html

{% extends "base.html" %}
{% block contents %}
    <div class="row mt-5">
        <div class="col-12">
            <h1>목록</h1>
        </div>
    </div>
    <div class="row mt-5">
        <div class="col-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th scope="col">글번호</th>
                    <th scope="col">제목</th>
                    <th scope="col">글쓴이</th>
                    <th scope="col">등록일</th>
                </tr>
                </thead>
                <tbody>
                {% for board in board_list %}
                    <tr scope="row">
                        <td>{{ board.id }}</td>
                        <td>{{ board.title }}</td>
                        <td>{{ board.insert_user }}</td>
                        <td>{{ board.insert_date|date:"Y-m-d" }}</td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
{% endblock %}
반응형