🍡 Django Tutorial - View Classes
Updated at 2018-11-23 18:28
Replace polls/views.py
:
from uuid import UUID
from django.http import HttpResponse, HttpRequest
from django.views import generic
from .models import Question
class PollListView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_questions'
def get_queryset(self):
return Question.objects.order_by('-created_at')[:5]
class PollDetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class PollResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request: HttpRequest, question_id: UUID) -> HttpResponse:
return HttpResponse("You're voting on question %s." % question_id)
Create polls/templates/polls/detail.html
:
<h1>{{ question.text }}</h1>
<ul>
{% for choice in question.choices.all %}
<li>{{ choice.text }}</li>
{% endfor %}
</ul>
Create polls/templates/polls/results.html
:
<h1>{{ question.text }}</h1>
<ul>
{% for choice in question.choices.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }}
vote{{ choice.votes|pluralize }}
</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
Edit polls/urls.py
:
# ...
urlpatterns = [
path('', views.PollListView.as_view(), name='index'),
path('<uuid:pk>/', views.PollDetailView.as_view(), name='detail'),
path('<uuid:pk>/results/', views.PollResultsView.as_view(), name='results'),
path('<uuid:question_id>/vote/', views.vote, name='vote'),
]
Above we are extending generic
views in django.views
.