Django Tutorial
View Function Handler

Updated at 2018-11-23 16:27

Create form for choice vote buttons, handle receiving the votes and show results.

Edit polls/templates/polls/detail.html:

<h1>{{ question.text }}</h1>

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

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

Edit polls/

from uuid import UUID

from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Question

# ...

def vote(request: HttpRequest, question_id: UUID):
    question = get_object_or_404(Question, pk=question_id)
        selected_choice = question.choices.get(pk=request.POST.get('choice'))
    except ObjectDoesNotExist:
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
    # increment with database operation avoiding race condition
    # use `with transaction.atomic():` for more complex operations
    selected_choice.votes = F('votes') + 1
    return HttpResponseRedirect(reverse('polls:results', kwargs={'pk':}))

Try out the new forms:

python runserver