Table of Contents
- Introduction
- Prerequisites
- Setting Up Django
- Creating the Django Project
- Building the To-Do List App
- Conclusion
Introduction
In this tutorial, we will build a To-Do List web application using Python and the Django web framework. By the end of this tutorial, you will have a functional web app that allows users to create, update, and delete tasks in their to-do list. This tutorial assumes you have basic knowledge of Python and web development concepts.
Prerequisites
Before starting this tutorial, make sure you have the following prerequisites:
- Python installed on your machine (version 3.6 or above)
- Basic understanding of Python concepts
- Familiarity with HTML and CSS (optional)
Setting Up Django
To begin, we need to install Django, which is a powerful Python web framework. Open your command line or terminal and run the following command to install Django:
python
pip install django
Once Django is installed, verify the installation by running the following command:
python
django-admin --version
You should see the installed version of Django printed on the screen. If there are no errors, you are ready to proceed.
Creating the Django Project
To create a new Django project, run the following command in your terminal:
python
django-admin startproject todoapp
This will create a new directory named todoapp
with a basic Django project structure. Navigate to the todoapp
directory using the cd
command:
python
cd todoapp
Now, let’s create a Django app within our project. Run the following command:
python
python manage.py startapp tasks
This will create a new directory named tasks
inside the todoapp
directory. This directory will contain all the files related to our To-Do List app.
Building the To-Do List App
Setting Up the Database
Before we can start building our app, we need to configure the database settings. In the settings.py
file inside the todoapp
directory, locate the DATABASES
dictionary and update it to match your database configuration. For this tutorial, we will use SQLite as the database backend.
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Creating the Task Model
In Django, models are used to define the structure of the database tables. Open the models.py
file inside the tasks
directory and define a new model class called Task
.
```python
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
``` This model has two fields: `title` and `completed`. The `title` field is a `CharField` that will store the title of the task, and the `completed` field is a `BooleanField` that will track whether the task is completed or not.
Creating the Views
Views in Django handle HTTP requests and return HTTP responses. Create a new file called views.py
inside the tasks
directory and add the following code:
```python
from django.shortcuts import render
from .models import Task
def index(request):
tasks = Task.objects.all()
return render(request, 'tasks/index.html', {'tasks': tasks})
``` This view function fetches all the tasks from the database and passes them to the template for rendering.
Creating the Templates
Templates in Django are used to generate HTML dynamically. Inside the tasks
directory, create a new directory called templates
if it doesn’t exist. Within the templates
directory, create another directory called tasks
. Inside the tasks
directory, create a new file called index.html
and add the following code:
```html
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<ul>
{% for task in tasks %}
<li>{{ task.title }}</li>
{% endfor %}
</ul>
</body>
</html>
``` This template renders the list of tasks fetched from the view.
Configuring the URLs
In Django, URLs are mapped to views using URL patterns. Open the urls.py
file inside the todoapp
directory and add the following code:
```python
from django.urls import path
from tasks.views import index
urlpatterns = [
path('', index, name='index'),
]
``` This configuration maps the root URL to the `index` view function.
Running the Development Server
Finally, let’s run the development server to see our app in action. In your terminal, run the following command:
python
python manage.py runserver
This will start the Django development server, and you should see an output similar to the following:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Open your web browser and navigate to http://127.0.0.1:8000/
. You should see the title “To-Do List” and an empty bullet list.
Adding Tasks
To add tasks to the to-do list, we need to create a form. Open the index.html
template and replace the existing code with the following:
```html
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form method="POST" action="{% url 'index' %}">
{% csrf_token %}
<input type="text" name="task_title">
<input type="submit" value="Add Task">
</form>
<ul>
{% for task in tasks %}
<li>{{ task.title }}</li>
{% endfor %}
</ul>
</body>
</html>
``` This code adds a form to the template where users can enter the title of a new task. When the form is submitted, it will make a POST request to the same URL with the task title as form data.
Saving Tasks
To handle the form submission and save the task to the database, we need to update the index
view function. Replace the existing index
function in views.py
with the following code:
```python
from django.shortcuts import render, redirect
from .models import Task
def index(request):
if request.method == 'POST':
title = request.POST['task_title']
Task.objects.create(title=title)
return redirect('index')
tasks = Task.objects.all()
return render(request, 'tasks/index.html', {'tasks': tasks})
``` This updated view function checks if the request method is POST, retrieves the task title from the form data, creates a new `Task` object, and redirects the user back to the homepage. If the request method is GET, it fetches all the tasks and renders the template as before.
Marking Tasks as Completed
Let’s add functionality to mark tasks as completed. Modify the index.html
template as follows:
```html
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form method="POST" action="{% url 'index' %}">
{% csrf_token %}
<input type="text" name="task_title">
<input type="submit" value="Add Task">
</form>
<ul>
{% for task in tasks %}
<li>
{{ task.title }}
<input type="checkbox" {% if task.completed %}checked{% endif %} onchange="this.form.submit()">
</li>
{% endfor %}
</ul>
</body>
</html>
``` This code adds a checkbox next to each task and updates the template to mark tasks as completed or not based on their `completed` field.
Updating the Model
To handle the task completion status, we need to update the Task
model. Open the models.py
file and add the following method to the Task
model class:
python
def toggle_completed(self):
self.completed = not self.completed
self.save()
This method toggles the completed
field and saves the object to the database.
Updating the View
Finally, modify the index
view function in views.py
to handle the task completion. Replace the existing index
function with the following code:
```python
from django.shortcuts import render, redirect
from .models import Task
def index(request):
if request.method == 'POST':
if 'task_title' in request.POST:
title = request.POST['task_title']
Task.objects.create(title=title)
else:
task_id = request.POST['task_id']
task = Task.objects.get(id=task_id)
task.toggle_completed()
return redirect('index')
tasks = Task.objects.all()
return render(request, 'tasks/index.html', {'tasks': tasks})
``` This updated view function checks if a task ID is present in the form data. If present, it retrieves the corresponding `Task` object, calls the `toggle_completed` method, and redirects the user back to the homepage.
Conclusion
Congratulations! You have successfully built a To-Do List web application using Python and Django. Throughout this tutorial, we covered the basics of Django, including setting up the project, creating models, views, templates, and handling form submissions. You can further enhance the app by adding features like task deletion, user authentication, and more.
Feel free to explore Django’s official documentation for more advanced concepts and features. Happy coding!