-
[Python] Class Based Views를 사용해보자Python/Django 2021. 12. 11. 00:23
# urls.py from django.urls import path from rooms import views as room_views app_name = "core" urlpatterns = [ path("", room_views.Homeview.as_view(), name="home"), ]
# views.py from django.views.generic import ListView from rooms import models as room_models # ListView 외에도 용도에 따라 많은 CBV 들이 존재한다 class Homeview(ListView): """HomeView Definition""" # 모델 지정 model = room_models.Room # 페이지 당 content 갯수 paginate_by = 10 # 마지막 페이지 최소 content 수량 설정 paginate_orphans = 5 # sort할 기준 (fields) ordering = "created" # query에서 page이름 아래의 예시) '/?page=1' page_kwarg = "page"
# home.html {% extends 'base.html' %} {% block page_name%} Home {% endblock %} {% block content %} # def views를 썼을 때에는 context를 전달해줘서 # kw를 맞춰줬어야 했는데 CBV에서 자동적으로 model.object.all()을 반환해주기 때문에 # object_list로 list에 접근하면 된다 {% for page in object_list %} <h1>{{page.name}} / ${{page.price}}</h1> {% endfor %} <h5> # attributes에 접근하려면 page_obj로 접근하면된다 {% if page_obj.has_previous %} <a href="/?page={{page_obj.previous_page_number}}">Previous</a> {% endif %} Page {{page_obj.number}} of {{page_obj.paginator.num_pages}} {% if page_obj.has_next %} <a href="/?page={{page_obj.next_page_number}}">Next</a> {% endif %} {% for page in page_obj.paginator.page_range %} <a href="/?page={{page}}">{{page}}</a> {% endfor %} </h5> {% endblock %}
'Python > Django' 카테고리의 다른 글
[Python] VSCode에서 Django 템플릿 오토 포매팅하기 (0) 2021.12.13 [Python] Django Class Based Views 정리 사이트 (0) 2021.12.11 [Python] Django의 Paginator로 쉽게 페이징 해주자 (0) 2021.12.10 [Python] shell 명령어를 만들고 사용해보자 (BaseCommand) (0) 2021.12.09 [Python] admin안에 admin을 넣어보자 (TabularInline, inlines) (0) 2021.12.08