Djangoでは、データの一覧表示、詳細表示、作成、更新、削除などの操作を
より簡単に実装することができように
汎用ビュー(generic view)というものを提供しています。
これまで作成してきた poll アプリのビューを汎用ビューシステムに変換して
コードを修正します。
URLconf の修正
polls/urls.py
urlpatterns = [
# ex: /polls/
path("", views.indexView.as_view(), name="index"),
# ex: /polls/5/
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
# ex: /polls/5/results/
path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
# ex: /polls/5/vote/
path("<int:question_id>/vote/", views.vote, name="vote"),
]
views の修正
polls/views.py
from django.views import generic
# Create your views here.
class IndexView(generic.ListView):
template_name = "polls/index.html"
context_object_name = "latest_question_list"
def get_queryset(self):
return Question.objects.order_by("-pub_date")[:5]
class DetailView(generic.DetailView):
model = Question
template_name = "polls/detail.html"
class ResultsView(generic.DetailView):
model = Question
template_name = "polls/results.html"
def vote(request, question_id):
... # same as above, no changes needed.
以上です。