본문 바로가기

Python/Python(Django)

Django tutorial part4. (Form 작성)

1. polls/template/polls/detail.html 에 Form을 작성해보자

{{ poll.question }}

{% if error_message %}

{{ error_message }}

{% endif %}
{% csrf_token %} {% for choice in poll.choice_set.all %}
{% endfor %}



2. polls/views.py 의 vote 함수를 수정해보자

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk = poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
                                                     'poll' : p, 
                                                     '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=(p.id,)))

request.POST['xxx'] 를 통해 전달받은 값을 가져온다.

request.GET['xxx'] 도 있다.

그리고 정상 처리 되면 "return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) " 형태로 리 다이렉트 하자




3. polls/template/polls/result.html 에 결과 페이지를 만들어 보자

{{ poll.question }}

    {% for choice in poll.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again?





반응형