Skip to content

Commit

Permalink
customize class based view
Browse files Browse the repository at this point in the history
  • Loading branch information
devjunhong committed Mar 15, 2020
1 parent fb3deda commit 9dca05e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
2 changes: 1 addition & 1 deletion polls/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('<int:question_id>/vote/', views.VoteView.as_view(), name='vote'),
]
33 changes: 29 additions & 4 deletions polls/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic.base import TemplateResponseMixin
from django.urls import reverse
from django.views import generic
from django.utils import timezone

from .models import Question
from .models import Question, Choice


def index(request):
Expand Down Expand Up @@ -48,10 +49,34 @@ def results(request, question_id):
return render(request, 'polls/results.html', {'question': question})


class ResultsView(generic.DetailView):
model = Question
class ResultsView(TemplateResponseMixin, generic.View):
template_name = 'polls/results.html'

def get_queryset(self, question_id):
return Question.objects.get(pk=question_id)

def get(self, request, pk):
queryset = self.get_queryset(pk)
context = {'question': queryset}
return self.render_to_response(context)


class VoteView(generic.View):
def get_queryset(self, choice_id):
return Choice.objects.get(pk=choice_id)

def post(self, request, question_id):
print('post')
choice_id = request.POST.get('choice', None)
try:
queryset = self.get_queryset(choice_id)
except (KeyError, Choice.DoesNotExist):
return redirect('polls:detail', pk=question_id)
else:
queryset.votes += 1
queryset.save()
return redirect('polls:results', pk=question_id)


def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
Expand Down

0 comments on commit 9dca05e

Please sign in to comment.