Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 77 ยท Projects

Project: Polls App

Build a complete Django polls app: Question and Choice models, a vote form, race-free voting with F(), results with annotate and a test suite. Run it live.

A poll is a small idea with a surprising number of real web-development problems inside it. Visitors read a question, pick one option and see the results. To make that work you need two related models, a form that only accepts valid choices, a write that stays correct when many people vote at once, a results page with totals and percentages, and tests that prove all of it.

In this project you build the whole app in your browser: models, forms, views, URLs, templates and a test suite. Nothing is copied from the official Django tutorial's "polls" app beyond the general idea of a poll; the design below is our own, and it adds closed polls, a safer vote form and percentage results.

Before you start, you should be comfortable with models, relationships, aggregation, forms, URL routing and testing basics.

What we are building

The app has four pages and two models. A poll (Question) owns several Choice rows, and each choice keeps its own vote counter.

erDiagram
    QUESTION ||--o{ CHOICE : has
    QUESTION {
        int id
        string text
        bool is_open
    }
    CHOICE {
        int id
        int question_id
        string text
        int votes
    }

One question has many choices; the vote count lives on the choice row.

URL View What it does
/polls/ index Lists polls with their number of choices and total votes
/polls/<id>/ detail Shows the question and a radio-button form
/polls/<id>/vote/ vote Accepts a POST, counts the vote, redirects to the results
/polls/<id>/results/ results Shows votes and percentages, most popular first

On your computer, each live example below would live in files: polls/models.py, polls/forms.py, polls/views.py, polls/urls.py and polls/templates/. The editors here put everything in one script, register a tiny in-memory polls app and keep templates in memory, because a browser tab has no project folder. The code itself is the same.

Step 1: the models and a counting bug

Start with the data. A Question has its text and an is_open flag, and a Choice belongs to a question through a ForeignKey with related_name="choices", so question.choices returns its options. Each Choice stores votes as a PositiveIntegerField.

The interesting part is how to add one vote. The obvious way is to load the row, add one in Python and save. That is a read-modify-write cycle, and it loses votes when two visitors overlap: both read 0, both write 1. The fix is an F expression, which tells the database to do the arithmetic itself in a single UPDATE ... SET votes = votes + 1 statement.

The editor below makes two stale copies of the same row to reproduce the race deterministically, then shows F() getting it right. It also builds the summary for the index page with annotate.

Python Models, a lost update and F()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the three results. The read-modify-write version ends with 1 instead of 2: the second save overwrote the first with a stale number. The F() version counted both votes because each UPDATE reads the current value inside the database. The same trick appears in the transactions lesson and in the URL shortener project for click counting.

The last query uses Count("choices") and Sum("choices__votes") to compute both numbers for every question in one SQL statement, and Coalesce(..., 0) turns the NULL that SUM returns for a poll without choices into a plain 0. Without it, the empty poll would show None votes.

Step 2: the form, the views and the templates

A vote form should accept only choices that belong to this poll. If you used a bare request.POST["choice"] lookup, a visitor could post the id of a choice from another poll and inflate it. A ModelChoiceField solves this when you restrict its queryset to the question's own choices. Django then validates the posted id against that queryset and produces a clear error otherwise.

Python
class VoteForm(forms.Form):
    choice = forms.ModelChoiceField(
        queryset=Choice.objects.none(),
        widget=forms.RadioSelect,
        empty_label=None,
        error_messages={"required": "Pick one option."},
    )

    def __init__(self, question, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["choice"].queryset = question.choices.all()

The queryset is set in __init__ because the question is only known at request time. RadioSelect renders one radio button per choice, and empty_label=None removes the blank "---------" option.

The four views are short on purpose. Notice what each one does and does not do:

  • index runs one annotated query and renders a template.
  • detail fetches the question with get_object_or_404 and renders an unbound form.
  • vote handles only POST (a GET is redirected back to the form), validates the form, applies the F() update and then redirects. Redirecting after a successful POST means a page refresh will not submit the vote again; this is the post/redirect/get pattern.
  • results aggregates the total once, then builds a row per choice with its percentage.

A closed poll or an invalid form re-renders the detail page with status 400, so clients and tests can tell that the vote was refused.

flowchart TD
    A["POST /polls/1/vote/"] --> B{"Poll open and<br/>form valid?"}
    B -- "no" --> C["Re-render detail page<br/>status 400, nothing saved"]
    B -- "yes" --> D["UPDATE choice<br/>SET votes = votes + 1"]
    D --> E["302 redirect to results"]
    E --> F["GET /polls/1/results/"]

The vote view either refuses the request or counts it with one atomic update, then redirects.

The next editor contains the complete app. It registers URLs under the polls namespace (so templates can use {% url 'polls:vote' question.pk %}), keeps four small templates in a memory loader with one shared base, and then plays the part of a browser with the test Client.

Python The complete polls app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the output from top to bottom. The index page shows both polls, including the one with no choices. The detail page contains three radio buttons. After four votes (three for Python, one for Go) the vote view answers 302 and points at the results page, where Python has 75% and Go 25%. The two invalid posts (nothing selected and choice 999) both return 400 with the form errors, and an unknown poll gives 404.

The results view computes percentages in Python from one aggregate total. That is fine for a handful of choices. If you ever need the percentage inside the database, for example to order by it, a window expression such as Window(Sum("votes"), partition_by=F("question_id")) does the same job in SQL.

Tip: the percentages are rounded independently, so they can add up to 99% or 101%. That is normal; if it matters, show one decimal place or use the "largest remainder" method.

Step 3: tests that protect the behavior

Every behavior worth having is worth a test. The tests below use django.test.TestCase, which wraps each test in a transaction that is rolled back afterwards, so tests never see each other's data. setUpTestData creates the shared poll once for the class, and self.client is a fresh test client for every test.

Choose tests by asking "what would hurt if it broke?":

  1. A vote adds exactly one and redirects to the results.
  2. Two votes in a row both count (this guards the F() update).
  3. A choice from another poll is rejected and nothing changes.
  4. A closed poll refuses votes.
  5. Results show the right percentages.
  6. The index page stays at one query however many polls exist (assertNumQueries).
  7. An unknown poll returns 404.

The editor below repeats the app code from step 2 (a real project would just import it) and then runs the test case programmatically, printing a short summary instead of the usual timing line so the output is stable.

Python Testing the polls app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Seven tests ran with no failures. To see a test earn its keep, go back to the editor, change the update(votes=F("votes") + 1) line in the vote view to a read-modify-write version, and think about which test would catch it. Then loosen the queryset in VoteForm to Choice.objects.all() and watch test_choice_from_another_poll_is_rejected fail. Breaking the code on purpose is one of the best ways to learn what each test guards.

Ideas for extending the project

When the app works, try these in your own project folder:

  • Add a closes_on date and make is_open a property; test it with a fixed date.
  • Register both models in the admin with Choice as a tabular inline of Question.
  • Require a signed-in user and add a Vote model with a unique constraint on (user, question), so each person votes once.
  • Add a JSON endpoint for the results, following the plain-Django API lesson.
  • Cache the results page for a few seconds with the low-level cache API.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the vote view use update(votes=F('votes') + 1) instead of choice.votes += 1 followed by save()?

    Read-modify-write copies the value into Python, so two overlapping requests can both write the same new number. An F() expression becomes a single UPDATE statement that the database applies to the current value.
  2. 2. How does the VoteForm stop a visitor from voting for a choice that belongs to a different poll?

    A ModelChoiceField only accepts primary keys that exist in its queryset. Restricting the queryset to question.choices.all() makes any other id invalid, no matter what the client posts.
  3. 3. Why does the vote view redirect after a successful POST?

    After a POST, refreshing the browser repeats that POST. Redirecting to a GET page (post/redirect/get) means a refresh just reloads the results.
  4. 4. What is Coalesce(Sum('choices__votes'), 0) used for in the index query?

    SUM over no rows is NULL, which Django returns as None. Coalesce supplies a default so the template can print a number.
  5. 5. Which test tool checks that a page does not run extra queries per row?

    assertNumQueries runs a block of code and fails if the number of SQL queries differs from the expected count.

Summary

  • Model a poll as Question plus Choice with a ForeignKey and related_name="choices"; keep the counter on the choice.
  • Increment counters with update(votes=F("votes") + 1); read-modify-write loses votes under concurrency.
  • Restrict a ModelChoiceField queryset to the current question so posted ids are validated against the right poll.
  • Use annotate with Count, Sum and Coalesce to build list summaries in one query.
  • Redirect after a successful POST, and answer invalid or refused POSTs with status 400.
  • Test the behavior that would hurt most if it broke: counting, rejection, results, query count and 404s.

Next lesson: Django Exercises with Solutions.