ListView, Pagination 소개 및 적용
class ArticleListView(ListView):
model = Article
context_object_name = 'article_list'
template_name = 'articleapp/list.html'
paginate_by = 3
ArticleListView를 만들어준다.
app_name = 'articleapp'
urlpatterns = [
path('list/', ArticleListView.as_view(), name='list'),
path('create/', ArticleCreateView.as_view(), name='create'),
path('detail/<int:pk>', ArticleDetailView.as_view(), name='detail'),
path('update/<int:pk>', ArticleUpdateView.as_view(), name='update'),
path('delete/<int:pk>', ArticleDeleteView.as_view(), name='delete'),
]
urls.py에서 ArticleListView설정을 해준다.
기존 list.html 내용을 지우고 우리가 작성한 게시글을 for문을 통해 출력하는 코드를 작성하자
{% if article_list %}
<div class="container">
{% for article in article_list %}
<a href="{% url 'articleapp:detail' pk=article.pk %}">
{% include 'snippets/card.html' with article=article %}
</a>
{% endfor %}
</div>
<script src="{% static 'js/magicgrid.js' %}"></script>
{% else %}
<div class="text-center">
<h1>No Articles YET!</h1>
</div>
{% endif %}
{% include 'snippets/pagination.html' with page_obj=page_obj %}
<div style="text-align: center">
<a href="{% url 'articleapp:create' %}" class="btn btn-dark rounded-pill col-3 mt-3 mb-3">
Create Article
</a>
</div>
for문을 통해 article_list에 있는 article를 card.html의 모양으로 출력을해준다.
나중에 출력 card 모양을 변경하고 싶거나 디자인을 변경하고 싶으면 card.html을 코드를 변경해주면된다.
그리고 페이지를 설정하는 코드인 pagination.html을 include해준다.
pagination.html 코드는 아래와 같다.
<div style="text-align: center; margin: 1rem 0;">
{% if page_obj.has_previous %}
<a href="{% url 'articleapp:list' %}?page={{page_obj.previous_page_number}}"
class="btn btn-secondary rounded-pill">
{{ page_obj.previous_page_number }}
</a>
{% endif %}
<a href="{% url 'articleapp:list' %}?page={{page_obj.number}}"
class="btn btn-secondary rounded-pill active">
{{ page_obj.number }}
</a>
{% if page_obj.has_next %}
<a href="{% url 'articleapp:list' %}?page={{page_obj.next_page_number}}"
class="btn btn-secondary rounded-pill">
{{ page_obj.next_page_number }}
</a>
{% endif %}
</div>
현재 페이지에서 이전 페이지와 다음 페이지가 있는지 없는지 확인하고 해당 페이지가 존재한다면 해당 페이지로 이동하는 링크를 만들어준다.
'기타 > django' 카테고리의 다른 글
작정하고 장고 - commentapp 만들기 (0) | 2023.05.31 |
---|---|
작정하고 장고 - articleapp 구현 (0) | 2023.05.26 |
작정하고 장고 - magicGrid (1) | 2023.05.24 |
작정하고 장고 - get_success_url 함수 (0) | 2023.05.24 |
작정하고 장고 - profile 마무리 (0) | 2023.05.24 |
댓글