본문 바로가기

Development (Python, Django, C..)

[Django] Tutorial 따라하기 - 4

* reference : https://docs.djangoproject.com/ko/2.1/intro/tutorial04/

 

첫 번째 장고 앱 작성하기, part 4 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

 

#. Make form

 

-- Add <form> to template

(djenv) ivan@django:~/djgo$ more polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

 

 

-- add vote() function to viws.py
-- modify results() function 

(djenv) ivan@django:~/djgo$ more polls/views.py
#from django.http      import Http404
from django.http      import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls      import reverse
#from django.template  import loader

from .models          import Question, Choice

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    #template = loader.get_template('polls/index.html')
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

def detail(request, question_id):
    #try:
    #    question = Question.objects.get(pk=question_id)
    #except Question.DoesNotExist:
    #    raise Http404("Question does not exist")
    #return render(request, 'polls/detail.html', {'question': question})
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})
    #response = "You're looking at the results of question %s."
    #return HttpResponse(response % question_id)

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_seg.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': qeustion,
            'error_message':"You didn't select a choice",
            })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

 

 

-- make result.html file

(djenv) ivan@django:~/djgo$ more polls/templates/polls/results.html
<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

 


 

 

#. Generic View

 

-- Change URLconf

(djenv) ivan@django:~/djgo$ more polls/urls.py
from django.urls import path
from . import views

app_name = 'polls'

urlpatterns = [
    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'   ),
]

 

 

-- change views.py to delete index, detail, results views and to use generic views

(djenv) ivan@django:~/djgo$ more polls/views.py
#from django.http      import Http404
from django.http      import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls      import reverse
from django.views import generic
#from django.template  import loader

from .models          import Question, Choice


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        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):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': qeustion,
            'error_message':"You didn't select a choice",
            })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))