CBV
이용하면 페이지를 간편하게 만들수 있다.
장고는 웹개발할때 사람들이 반복해서 사용하는 기능들을 클래스형태로 제공해준다.
ListView 클래스
목록 리스트 만들기 위해서 ListView 클래스를 활용한다.
FBV 방식으로 만든 함수 방식 대신 ListView 클래스를 상속해 만든다.
notice/views.py
from django.views.generic import ListView
from .models import Notice #model은 Notice라고 선언.
# Create your views here.
class NoticeList(ListView):
model = Notice
notice/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.NoticeList.as_view()),
]
notice/notice_list.html
작성하기
장고가 제공하는 ListView 모델뒤에 _list가 붙은 html파일을 기본 템플릿으로 사용하도록 설정되어 있다.
Question 모델을 사용하면 question_list.html이 필요하다.
_list.html 작성하는 두가지 방법
1. _list.html 이름이 아닌경우 PostList클래스에 template_name='notice/리스트가나올html'
notice/views.py
from django.views.generic import ListView
from .models import Notice
# Create your views here.
class NoticeList(ListView):
model = Notice
template_name='notice/index.html(리스트가나올html)'
#임의의 명의로 index.html이라고 했다.
ListView로 만든 클래스의 모델 객체를 가져오려면 object_list 명령어를 사용한다.
question 모델을 사용해서 notice_list라고 쓰면 자동으로 인식한다.
.html에 notice_list 또는 object_list 써서 불러온다.
notice/index.html
<h1>공지사항</h1>
{% for n in notice_list %}
<hr>
<h2><a href="{{n.get_absolute_url}}">{{n.subject}}</a></h2>
<h4>{{n.created}}</h4>
<p>{{n.conent}}</p>
{% endfor %}
2. index.html 파일을 이름을 notice_list.html로 수정한다.(오른쪽클릭→Refactor→Rename)
notice/views.py 작성한 template_name='notice/index.html(리스트가나올html)' 삭제한다.
템플릿명을 명시하지않으면 notice_list.html을 템플릿으로 인식하기때문에 html을 notice_list.html로 바꾸면 인식한다.
notice/views.py
from django.views.generic import ListView
from .models import Notice
# Create your views here.
class NoticeList(ListView):
model = Notice
ordering='-pk'
views.py에 DetailView를 추가한다.
notice/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:pk>/',views.NoticeDetail.as_view()),
path('', views.NoticeList.as_view()),
]
path('<int:pk>/',views.NoticeDetail.as_view()), 를 추가한다.
tmemplate_name을 추가하지 않고 html을 notice_detail.html로 이름을 수정한다.
댓글