<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>
// polls/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question
# ...
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):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
** reverse() 함수가 특이하다. 이 함수는 뷰함수에 URL을 하드코딩하지 않도록 도와준다. redirect하기를 원하는 뷰의 이름을 URL패턴의 변수수분을 조합해서 해당 뷰를 가르키도록 하다.
// polls/views.py
from django.shortcuts import get_object_or_404, render
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
전달된 파라미터에 따라 DB에서 데이터를 가져오고 템플릿에 랜더링하는 일반적인 패턴을 위해 Django에서는 'Generic view' 시스템이라는 간단한 방식을 지원한다.
제너릭 뷰는 위와 같은 일반적인 패턴을 추상화하여 Python 코드를 작성하지 않아도 된다.
1. URLconf를 수정
URLconf 수정
- urlpattenr 수정
views 수정
- import django.views import generic