티스토리 뷰

   ● 상품 목록 (ListView ver.)    

 

product/views.py(ListView)

- ListView는 조건에 맞는 여러 개의 객체를 보여준다. 보여주려는 객체(model)를 Product로 정의한다. 그러면 Product 객체의 정보를 QuerySet으로 받아와서 template_name 에 연결된 html로 넘겨준다. 

class ProductList(ListView):
    model = Product
    template_name = 'product_list.html'

 

 

templates/product_list.html

- ProductList 에서 받아온 product 객체 정보는 object_list에 저장된다.  객체리스트에는 여러 개의 product 객체 정보가 담겨있고, 그것을 하나씩 가져와서 화면에 출력하면 된다.  

{% extends 'base.html' %}
{% load humanize %}
{% block contents %}
<div class = "row mt-5">
    <div class = "col-12">
        <table class = "table table-dark">
            <thead class = "thead thead-dark">
                <td scope = "col">No.</td>
                <td scope = "col">상품명</td>
                <td scope = "col">가격</td>
                <td scope = "col">등록 날짜</td>
            </thead>
            <tbody class = "text-light">
                {% for product in object_list %}
                <tr>
                    <td scope = "col">{{product.id}}</td>
                    <td>{{ product.name }}</td>
                    <td>{{ product.price | intcomma }}원</td>
                    <td>{{ product.registered_date | date:'Y-m-d H:i'}}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endblock %}

 

- 세자리 단위로 콤마를 찍기 위해 {% load humanize %} 를 상단에 추가한다. 그런데 settings.py INSTALLED_APP 에 'django.contrib.humanize' 추가해야 아래와 같은 오류가 발생하지 않는다.

 

 

상품 목록 페이지

댓글