Hello there, aspiring web developer! Ever wanted to build your own website or web application but felt overwhelmed by where to start? You’re in luck! Today, we’re going to take a fun and practical first step together: creating a simple To-Do List application using a powerful web framework called Django.
A To-Do List app is a fantastic project for beginners because it covers many fundamental concepts without being too complicated. By the end of this guide, you’ll have a basic application running that can display a list of tasks – a solid foundation for more complex projects!
What is Django?
Let’s start with the star of our show: Django.
Imagine you want to build a house. You could gather every single brick, piece of wood, and nail yourself, and design everything from scratch. Or, you could use a pre-built kit that provides you with walls, roofs, and windows, letting you focus on the interior design and unique touches.
Django is like that pre-built kit for websites. It’s a web framework (a toolkit of pre-written code) that helps you build robust and scalable web applications quickly, without having to reinvent the wheel for common web development tasks. It’s written in Python, a very beginner-friendly programming language.
Getting Started: Setting Up Your Environment
Before we dive into coding, we need to set up our workspace. Think of it as preparing your construction site!
Prerequisites
You’ll need a few things installed on your computer:
- Python: Make sure you have Python 3 installed. You can download it from the official Python website.
- pip: This is Python’s package installer, usually comes with Python. We’ll use it to install Django.
- A Text Editor: Visual Studio Code, Sublime Text, Atom, or even a simple Notepad++ will work!
Creating a Virtual Environment
It’s good practice to create a virtual environment for each of your Python projects. This keeps the packages (like Django) for one project separate from others, preventing conflicts.
- Create a project folder:
bash
mkdir my_todo_project
cd my_todo_project - Create the virtual environment:
bash
python -m venv venv
Explanation:python -m venv venvtells Python to create a new virtual environment namedvenvinside your project folder. - Activate the virtual environment:
- On Windows:
bash
.\venv\Scripts\activate - On macOS/Linux:
bash
source venv/bin/activate
You’ll see(venv)appear at the start of your command prompt, indicating that your virtual environment is active.
- On Windows:
- Install Django: Now, with your virtual environment active, install Django using
pip.
bash
pip install django
Starting Your Django Project
With Django installed, let’s create our first Django project.
-
Start a new project:
bash
django-admin startproject todo_project .
Explanation:django-adminis the command-line tool Django provides.startprojectis the command to create a new project.todo_projectis the name of our main project..(the dot) tells Django to create the project files in the current directory, instead of creating another nested folder.
After this, you’ll see a structure like this:
my_todo_project/
├── venv/
├── todo_project/
│ ├── __init__.py
│ ├── settings.py # Project settings
│ ├── urls.py # Project URL definitions
│ └── wsgi.py
├── manage.py # A utility script to interact with your project
2. Run the development server: Let’s make sure everything is set up correctly.
bash
python manage.py runserver
You should see output similar to:
“`
Watching for file changes with StatReloader
Performing system checks…System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.
September 10, 2023 – 10:00:00
Django version 4.2.5, using settings ‘todo_project.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
``http://127.0.0.1:8000/
Open your web browser and go to. You should see a "The install worked successfully! Congratulations!" page. This means your Django project is up and running! PressCTRL+C` in your terminal to stop the server for now.
Creating a Django App
In Django, projects are made of smaller, reusable components called apps. Think of the todo_project as the entire house, and an app as a specific room (like the kitchen or bedroom) that has a specific purpose. We’ll create an app specifically for our To-Do list functionality.
-
Create a new app:
bash
python manage.py startapp todo
This creates a new folder namedtodoinsidemy_todo_project/with its own set of files. -
Register your app: Django needs to know about your new
todoapp. Opentodo_project/settings.pyand add'todo'to theINSTALLED_APPSlist.“`python
todo_project/settings.py
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘todo’, # <— Add your app here
]
“`
Defining Your To-Do Model
Now, let’s define what a “task” in our To-Do list should look like. In Django, we do this using models. A model is like a blueprint for the data you want to store in your database. Django’s models also provide an easy way to interact with your database without writing complex SQL code (this is called an ORM – Object-Relational Mapper).
-
Open
todo/models.pyand define yourTaskmodel:“`python
todo/models.py
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200) # A short text for the task name
description = models.TextField(blank=True, null=True) # Longer text, optional
created_at = models.DateTimeField(auto_now_add=True) # Date and time created, set automatically
completed = models.BooleanField(default=False) # True if task is done, False otherwisedef __str__(self): return self.title # How a Task object will be displayed (e.g., in the admin)``models.Model
*Explanation:*
*means ourTaskclass inherits all the good stuff from Django's model system.title
*: ACharField(character field) for short text, with a maximum length.description
*: ATextFieldfor longer text.blank=Truemeans it's not required to fill this field in forms, andnull=Trueallows the database field to be empty.created_at
*: ADateTimeFieldthat automatically sets the current date and time when a task is created (auto_now_add=True).completed
*: ABooleanField(true/false) with a default value ofFalse.str(self)`: This special method defines how an object of this model will be represented as a string. It’s helpful for displaying objects in the admin panel.
* -
Make migrations: After defining your model, you need to tell Django to create the necessary tables in your database.
bash
python manage.py makemigrations
This command creates migration files that describe the changes to your database schema. You’ll see something likeMigrations for 'todo': 0001_initial.py. -
Apply migrations: Now, apply those changes to your actual database.
bash
python manage.py migrate
This command executes the migration files, creating theTasktable (and other default Django tables) in your database.
Making It Visible: The Admin Panel
Django comes with a powerful, ready-to-use admin panel. It’s a web interface that allows you to manage your data easily. Let’s make our Task model accessible through it.
-
Create a superuser: This is an administrator account for your Django project.
bash
python manage.py createsuperuser
Follow the prompts to create a username, email (optional), and password. -
Register your model: Open
todo/admin.pyand register yourTaskmodel:
“`python
# todo/admin.pyfrom django.contrib import admin
from .models import Taskadmin.site.register(Task)
“` -
Run the server again:
bash
python manage.py runserver
Go tohttp://127.0.0.1:8000/admin/in your browser. Log in with the superuser credentials you just created. You should now see “Tasks” under the “TODO” section. Click on “Tasks” to add a new task, view, or edit existing ones! This is a great way to quickly add some sample data.
Basic Views and URLs
Now that we can store tasks, let’s display them to users! This involves two main components: views and URLs.
- A view is a Python function (or class) that takes a web request and returns a web response. It’s like the “brain” that decides what data to get from the model and what to show on the webpage.
-
A URL (Uniform Resource Locator) is the web address that users type into their browser. We need to tell Django which view should handle which URL.
-
Create a view: Open
todo/views.pyand add a function to display tasks:
“`python
# todo/views.pyfrom django.shortcuts import render
from .models import Task # Import our Task modeldef task_list(request):
tasks = Task.objects.all().order_by(‘-created_at’) # Get all tasks, newest first
return render(request, ‘todo/task_list.html’, {‘tasks’: tasks})
``task_list(request)
*Explanation:*
*: This is our view function. It takes arequestobject as an argument.tasks = Task.objects.all().order_by(‘-created_at’)
*: This line uses ourTaskmodel to fetch all tasks from the database and orders them by their creation date, with the newest first (the–sign means descending order).render(request, ‘todo/task_list.html’, {‘tasks’: tasks})
*: This is a shortcut function that combines a request, a **template** (an HTML file), and a dictionary of data ({‘tasks’: tasks}) into an HTTP response. It means "render thetask_list.htmlfile, and make thetasks` variable available inside it.” -
Define URLs for the app: Create a new file inside your
todoapp folder namedurls.py.“`python
todo/urls.py
from django.urls import path
from . import views # Import our views from the current appurlpatterns = [
path(”, views.task_list, name=’task_list’), # Our root URL for the app
]
``path(”, views.task_list, name=’task_list’)
*Explanation:*
*: This maps the empty path (meaninghttp://127.0.0.1:8000/todo/if we set it up that way) to ourtask_listview.name=’task_list’` gives this URL a memorable name for later use. -
Include app URLs in the project’s URLs: We need to tell the main
todo_projectabout the URLs defined in ourtodoapp. Opentodo_project/urls.py.“`python
todo_project/urls.py
from django.contrib import admin
from django.urls import path, include # Import includeurlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘todo/’, include(‘todo.urls’)), # <— Add this line
]
``path(‘todo/’, include(‘todo.urls’))
*Explanation:*
*: This tells Django that any URL starting withtodo/should be handed over to the URL patterns defined in ourtodoapp'surls.py. So, if you go tohttp://127.0.0.1:8000/todo/, it will use thetask_list` view we defined.
Creating a Simple Template
Finally, let’s create the HTML file that our task_list view will render to display the tasks. Django uses templates to separate Python code logic from the presentation (HTML).
-
Create a
templatesdirectory: Inside yourtodoapp folder, create a new folder namedtemplates. Insidetemplates, create another folder namedtodo. This structure (app_name/templates/app_name/) is a best practice to avoid conflicts if you have multiple apps with similarly named templates.
my_todo_project/
├── ...
├── todo/
│ ├── migrations/
│ ├── templates/
│ │ └── todo/ # <--- New folder
│ │ └── task_list.html # <--- New file
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py # <--- New file
│ └── views.py
├── ... -
Create
task_list.html: Opentodo/templates/todo/task_list.htmland add this HTML:
“`html
<!DOCTYPE html>
My To-Do List
My To-Do List
{% if tasks %} {# Check if there are any tasks #} <ul> {% for task in tasks %} {# Loop through each task #} <li class="{% if task.completed %}completed{% endif %}"> <h2>{{ task.title }}</h2> {% if task.description %} <p class="description">{{ task.description }}</p> {% endif %} <small>Created: {{ task.created_at|date:"M d, Y" }}</small><br> <small>Status: {% if task.completed %}Completed{% else %}Pending{% endif %}</small> </li> {% endfor %} </ul> {% else %} {# If no tasks #} <p>No tasks yet! Time to add some in the admin panel.</p> {% endif %}
``{% if tasks %}
*Explanation:*
*and{% for task in tasks %}: These are Django's **template tags**. They allow you to add basic logic (likeifstatements andforloops) directly into your HTML.{{ task.title }}
*: This is a **template variable**. It displays the value of thetitleattribute of thetaskobject passed from the view.{{ task.created_at|date:”M d, Y” }}
*: This uses a **template filter** (|date:”M d, Y”`) to format the date nicely.
Seeing Your To-Do List in Action!
- Run the server again (if it’s not already running):
bash
python manage.py runserver - Open your browser and navigate to
http://127.0.0.1:8000/todo/.
You should now see your very own To-Do List, displaying any tasks you added through the admin panel! How cool is that?
Conclusion
Congratulations! You’ve just taken a significant step into the world of web development with Django. In this guide, you’ve learned to:
- Set up a Django project and app.
- Define a data model (
Task). - Manage your data using the Django admin panel.
- Create a view to fetch data.
- Map URLs to your views.
- Display data using Django templates.
This is just the beginning! From here, you can expand this application by adding features like:
* Forms to add new tasks directly from the main page.
* Buttons to mark tasks as completed.
* User authentication so different users have their own To-Do lists.
Keep exploring, keep building, and have fun on your coding journey!
Leave a Reply
You must be logged in to post a comment.