Python and Django: Building a Polling App

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the Django Project
  5. Creating the Polls App
  6. Defining Models
  7. Creating Views
  8. Creating Templates
  9. Accessing the App
  10. Conclusion

Introduction

In this tutorial, we will learn how to build a polling app using Python and the Django web framework. By the end of this tutorial, you will have a fully functional polling app where users can vote on different poll options.

Prerequisites

Before starting this tutorial, you should have a basic understanding of the Python programming language. Familiarity with HTML, CSS, and JavaScript will also be helpful, but not required.

You will need the following software installed on your machine:

  • Python (version 3 or higher)
  • Django (version 3 or higher)

Setup

To get started, let’s set up a new Django project and create a virtual environment. Open your terminal and follow these steps:

  1. Create a new directory for your project: mkdir polling-app
  2. Change into the project directory: cd polling-app
  3. Create a new virtual environment: python3 -m venv env
  4. Activate the virtual environment:
    • For macOS/Linux: source env/bin/activate
    • For Windows: .\env\Scripts\activate

Now that we have our virtual environment set up, let’s install Django. Run the following command: pip install django With Django installed, we are ready to start building our polling app.

Creating the Django Project

In Django, a project is a collection of settings and configurations for a specific website. Let’s create a new Django project called polling_project. Run the following command: django-admin startproject polling_project . This will create a new Django project with the name polling_project in the current directory. The . at the end of the command is important and tells Django to create the project in the current directory.

Creating the Polls App

Next, we will create a Django app within our project to handle the polls functionality. Change into the project directory if you’re not already in it and run the following command: python manage.py startapp polls This will create a new directory called polls containing the necessary files for our app.

Defining Models

Models in Django are used to define the structure and behavior of data stored in the database. In our polling app, we will use models to define the Poll and Choice objects.

Open the polls/models.py file and replace its contents with the following code: ```python from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
``` In this code, we define two models: `Poll` and `Choice`. The `Poll` model has two fields: `question` and `pub_date`. The `Choice` model has three fields: `poll` (a foreign key to `Poll`), `choice_text`, and `votes`.

Notice that we import the models module from django.db. This module provides all the necessary tools to create and manipulate database models.

After defining our models, we need to create the corresponding database tables. Run the following command: python manage.py makemigrations python manage.py migrate The first command (makemigrations) creates migration files based on the models you defined. The second command (migrate) applies those migrations to create the database tables.

Creating Views

Views in Django are functions or classes that handle a user’s request and return a response. In our polling app, we will create views to display the polls and handle the voting logic.

Open the polls/views.py file and replace its contents with the following code: ```python from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse

from .models import Choice, Poll

def index(request):
    latest_polls = Poll.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', {'latest_polls': latest_polls})

def detail(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/detail.html', {'poll': poll})

def vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    selected_choice = poll.choice_set.get(pk=request.POST['choice'])
    selected_choice.votes += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('polls:results', args=(poll_id,)))

def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/results.html', {'poll': poll})
``` In this code, we define four views: `index`, `detail`, `vote`, and `results`. The `index` view displays the latest polls, the `detail` view shows the details of a specific poll, the `vote` view handles the voting logic, and the `results` view displays the results of a poll.

Creating Templates

Templates in Django are used to generate HTML dynamically. We will create HTML templates to define the structure and layout of our app’s pages.

First, create a new directory called templates inside the polls directory. Then, create the following HTML files inside the templates/polls directory:

  • index.html
  • detail.html
  • results.html

Open each file and add the following content:

index.html ```html

``` **detail.html**
```html

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

``` **results.html**
```html

<h2>{{ poll.question }}</h2>
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} - {{ choice.votes }} vote{% if choice.votes != 1 %}s{% endif %}</li>
{% endfor %}
</ul>

``` These template files use Django's template language to dynamically render the poll data.

Accessing the App

To access our polling app, we need to configure the URL routing. Open the polling_project/urls.py file and replace its contents with the following code: ```python from django.contrib import admin from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
]
``` This code configures two URL patterns: one for the Django admin site and one for our polls app.

Next, create a new file called urls.py inside the polls directory and add the following code: ```python from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:poll_id>/', views.detail, name='detail'),
    path('<int:poll_id>/vote/', views.vote, name='vote'),
    path('<int:poll_id>/results/', views.results, name='results'),
]
``` This code defines the URL patterns for our app's views. Each view is mapped to a specific URL pattern and has a corresponding name that we can use in our templates.

Finally, run the following command to start the development server: python manage.py runserver Open your web browser and access http://localhost:8000/polls/ to see the list of latest polls. Click on a poll to view its details, vote, and see the results.

Conclusion

In this tutorial, we have learned how to build a simple polling app using Python and the Django web framework. We covered the key concepts of Django, including models, views, templates, and URL routing.

By following this tutorial, you should now have a good understanding of how to create a basic web application using Python and Django. You can further extend this app by adding authentication, more complex models, and additional views.

Keep exploring Django’s documentation and experimenting with different features to enhance your web development skills. Happy coding!