Welcome, aspiring web developers! Today, we’re going to embark on an exciting journey to build a simple web application using Django. If you’ve ever wanted to create something interactive on the web but felt overwhelmed, this guide is for you! We’ll break down each step, explaining everything in simple terms.
What Are We Building Today?
We’re going to create a basic “polling” application. Think of it like a simple survey where people can see a question and, eventually, pick an answer. For this guide, we’ll focus on setting up the project, defining our questions, and displaying them on a web page. It’s a fantastic starting point to understand the fundamentals of web development with Django.
A Quick Chat About Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. What does that mean?
* Web Framework: It’s a collection of tools and guidelines that help you build websites and web applications faster and more efficiently. Instead of writing everything from scratch, Django provides ready-made components for common web tasks.
* High-level: It abstracts away many complex details, allowing you to focus on your application’s unique features.
* Python: It’s written in Python, a popular, easy-to-learn programming language.
Django is often called a “batteries-included” framework because it comes with many features built-in, like an admin interface, an Object-Relational Mapper (ORM) for databases, and a templating system.
What is a Polling App?
A polling app is a web application where users can vote on predefined questions. Imagine a question like “What’s your favorite programming language?” with options like “Python,” “JavaScript,” “Java,” etc. Our app will store these questions and choices, and we’ll learn how to display them on a web page.
Getting Started: Prerequisites
Before we dive into code, make sure you have these things ready:
- Python Installed: Django is a Python framework, so you need Python 3 installed on your computer. You can download it from the official Python website.
- Command Line Knowledge: We’ll be using your computer’s command line (Terminal on macOS/Linux, Command Prompt or PowerShell on Windows) to run commands. Don’t worry if you’re new to it; we’ll guide you through.
Setting Up Your Development Environment
It’s good practice to create a “virtual environment” for each Django project.
What is a Virtual Environment?
A virtual environment is like a self-contained box for your project’s Python packages (like Django). It keeps your project’s dependencies separate from other Python projects on your computer. This prevents conflicts and makes managing project-specific packages much easier.
Let’s create one:
- Open your command line.
- Navigate to where you want to store your project. For example, you might create a folder called
django_projects.
bash
mkdir django_projects
cd django_projects - Create the virtual environment:
bash
python -m venv myenvpython -m venv: This command uses Python’s built-invenvmodule to create a virtual environment.myenv: This is the name of our virtual environment. You can call it anything, butmyenvorvenvis common.
- Activate the virtual environment:
- On macOS/Linux:
bash
source myenv/bin/activate - On Windows (Command Prompt):
bash
myenv\Scripts\activate - On Windows (PowerShell):
bash
myenv\Scripts\Activate.ps1
You’ll know it’s active when you see(myenv)at the beginning of your command line prompt.
- On macOS/Linux:
Installing Django
Now that your virtual environment is active, let’s install Django:
pip install Django
pip: This is Python’s package installer. It’s used to install software packages written in Python.install Django: This command tellspipto download and install the Django framework into your active virtual environment.
Creating Your First Django Project
A Django project is the main container for your web application. It holds configuration files and one or more “apps.”
-
Create the Django project:
bash
django-admin startproject mysite .django-admin: This is Django’s command-line utility for administrative tasks.startproject: This command creates a new Django project.mysite: This is the name of our project..: This dot is important! It tells Django to create the project files in the current directory (django_projects/in our example), rather than creating another nestedmysite/mysitefolder.
After running this, your directory structure should look something like this:
django_projects/
├── myenv/
├── mysite/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.pymysite/(outer): This is your project’s root directory.manage.py: A command-line utility that lets you interact with this Django project.mysite/(inner): This contains your project’s actual Python packages and settings.settings.py: Where you configure your Django project (database, installed apps, etc.).urls.py: Where you define URL patterns for your entire project.
-
Run the development server:
bash
python manage.py runserver
This command starts Django’s built-in development web server. It’s super useful for testing your application locally without needing to set up a full-blown web server like Apache or Nginx.You should see output similar to this:
...
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Open your web browser and go tohttp://127.0.0.1:8000/. You should see a “The install worked successfully! Congratulations!” page. This means Django is running!To stop the server, go back to your command line and press
CTRL+C.
Creating a Django App for Our Poll
In Django, projects are made up of “apps.” An app is a self-contained module that does one thing well, like a blog app, a comments app, or in our case, a polls app. This modularity makes your project organized and reusable.
-
Create the
pollsapp: Make sure you are in the directory containingmanage.py(i.e.,django_projects/mysite/).
bash
python manage.py startapp polls
This creates apollsdirectory with its own set of files:
mysite/
├── polls/
│ ├── migrations/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── mysite/
└── manage.pymodels.py: Where you define your database structure.views.py: Where you write the logic for handling web requests and returning responses.admin.py: Where you register your models to be accessible via the Django admin interface.
-
Register the
pollsapp: Django needs to know that your project uses this new app.
Openmysite/settings.pyand find theINSTALLED_APPSlist. Add'polls'to it:“`python
mysite/settings.py
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘polls’, # Add your new app here!
]
“`
Defining Our Data: Models
Now it’s time to define what a “question” and a “choice” look like for our poll. In Django, we do this using models.
What are Models?
A model is a Python class that represents a table in your database. It defines the fields (columns) and behaviors of the data you want to store. Django’s built-in Object-Relational Mapper (ORM) handles the communication with the database for you, so you don’t have to write complex SQL queries directly. You interact with Python objects instead!
Open polls/models.py and add the following code:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Let’s break down these models:
-
QuestionModel:question_text: A field to store the actual question, limited to 200 characters (CharField).pub_date: A field to store the date and time the question was published (DateTimeField).__str__method: This is a Python special method that tells Django what to display when it needs a string representation of aQuestionobject (e.g., in the admin interface).
-
ChoiceModel:question: AForeignKeyfield. This creates a link betweenChoiceandQuestion. It means eachChoicebelongs to a singleQuestion.on_delete=models.CASCADEmeans if aQuestionis deleted, all its associatedChoices will also be deleted.choice_text: The text of the choice itself (e.g., “Yes”, “No”, “Maybe”).votes: AnIntegerFieldto store the number of votes for this choice, defaulting to 0.
Creating Database Tables (Migrations)
After defining our models, we need to tell Django to create the corresponding tables in our database. This is done through migrations.
Migrations are Django’s way of propagating changes you make to your models (like adding a field, deleting a model, etc.) into your database schema.
-
Create migration files:
bash
python manage.py makemigrations polls
This command looks at yourmodels.pyfile, compares it to the current state of your database, and creates migration files (Python files that describe the changes needed). You should see output indicating a0001_initial.pyfile was created inpolls/migrations/. -
Apply migrations to the database:
bash
python manage.py migrate
This command applies all pending migrations to your database. It will create the tables for yourQuestionandChoicemodels, as well as tables for Django’s built-in features (like user authentication).
The Django Admin Interface
Django comes with a powerful, production-ready admin interface automatically generated from your models. It’s a great way to manage data without writing any code.
-
Create a superuser: This is an administrator account for the Django admin.
bash
python manage.py createsuperuser
Follow the prompts to create a username, email, and password. -
Register your models with the admin:
Openpolls/admin.pyand add your models:“`python
polls/admin.py
from django.contrib import admin
from .models import Question, Choiceadmin.site.register(Question)
admin.site.register(Choice)
``Question
This tells the Django admin to display yourandChoice` models. -
Run the server and visit the admin:
bash
python manage.py runserver
Open your browser and go tohttp://127.0.0.1:8000/admin/. Log in with the superuser credentials you just created. You should now see “Questions” and “Choices” under the “POLLS” section, allowing you to add and manage your poll data! Go ahead and add a few questions and choices.
Building Our First View
A view in Django is a Python function (or class) that takes a web request and returns a web response. It contains the logic for what happens when a user visits a particular URL.
Open polls/views.py and let’s create a simple view to display our questions:
from django.shortcuts import render
from django.http import HttpResponse # We'll use this later, but for now we'll use render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(request, 'polls/index.html', context)
Let’s break this down:
from django.shortcuts import render:renderis a helper function that takes the request, a template name, and a dictionary of context variables, and returns anHttpResponseobject with the rendered template.from .models import Question: We import ourQuestionmodel so we can interact with our database.index(request): This is our view function. It takes anHttpRequestobject (request) as its first argument.latest_question_list = Question.objects.order_by('-pub_date')[:5]: This is where our ORM comes in handy!Question.objects: This is Django’s manager for theQuestionmodel, allowing us to query the database.order_by('-pub_date'): Sorts the questions bypub_datein descending order (newest first).[:5]: Slices the list to get only the latest 5 questions.
context = { ... }: A dictionary that maps context variable names (which we’ll use in our template) to Python objects.return render(request, 'polls/index.html', context): This tells Django to load the template namedpolls/index.html, pass it thecontextdictionary, and return the rendered HTML as the response.
Mapping URLs to Views
How does Django know which view to call when a user visits a specific URL? Through URL patterns!
First, create a urls.py file inside your polls app directory:
touch polls/urls.py
Now, open polls/urls.py and add the following:
from django.urls import path
from . import views
app_name = 'polls' # Helps Django distinguish URL names between different apps
urlpatterns = [
path('', views.index, name='index'),
]
from django.urls import path: Imports thepathfunction, used to define URL patterns.from . import views: Imports theviews.pymodule from the current directory.path('', views.index, name='index'): This defines a URL pattern.'': An empty string means this URL pattern will match the root of the app’s URL (e.g.,/polls/).views.index: Tells Django to call theindexfunction inviews.pywhen this URL is visited.name='index': Gives this URL a name, which is useful for referring to it elsewhere in Django (e.g., in templates).
Next, we need to “include” our polls app’s URLs into the main project’s urls.py.
Open mysite/urls.py and modify it:
from django.contrib import admin
from django.urls import include, path # Make sure to import 'include'
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls')), # Include our polls app's URLs here
]
from django.urls import include, path: We addedinclude.path('polls/', include('polls.urls')): This means that any URL starting withpolls/will be handled by the URL patterns defined inpolls/urls.py. So, ourindexview will be accessible at/polls/.
Creating Our First Template
Our view is now ready to send data to a template. A template is essentially an HTML file that can contain dynamic content using Django’s template language. This allows us to separate our website’s logic (in views) from its presentation (in templates).
- Create a
templatesdirectory: Inside yourpollsapp directory, create a new folder calledtemplates. Insidetemplates, create another folder calledpolls. This nested structure (polls/templates/polls/) is a best practice to prevent naming conflicts with templates from other apps.
bash
# In your command line, inside the polls directory:
mkdir -p polls/templates/polls -
Create
index.html:
Insidepolls/templates/polls/, create a new file namedindex.html.“`html
<!DOCTYPE html>
Our Simple Polls App
Latest Poll Questions
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li>{{ question.question_text }} (Published: {{ question.pub_date }})</li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
``{% if latest_question_list %}
In this template:
*and{% for question in latest_question_list %}are Django template tags. They allow you to add logic (like if/else conditions and loops) directly into your HTML.{{ question.question_text }}
*and{{ question.pub_date }}are template variables. Django replaces these with the actual values from thequestionobject passed in thecontext` dictionary from our view.
Seeing It All Come Together!
Alright, it’s time to test our polling app!
- Start your Django development server (if not already running):
bash
python manage.py runserver - Open your browser and navigate to
http://127.0.0.1:8000/polls/.
You should now see a list of the questions you added through the Django admin interface! If you added no questions, it will display “No polls are available.”
Congratulations! You’ve successfully built a basic web application with Django, defining models, creating views, mapping URLs, and rendering templates.
Next Steps
This is just the beginning! Here are some ideas to continue expanding your polling app:
- Detail View: Create a page for each individual question that shows its choices.
- Voting Mechanism: Add forms to allow users to vote on choices and update the
votescount. - Results Page: Display the results of a poll, showing how many votes each choice received.
- Styling: Make your app look even better with more advanced CSS.
Keep exploring, keep building, and happy coding!
Leave a Reply
You must be logged in to post a comment.