The in this article, you can get training on creating a robust and functional To-Do List application using Django. This project serves as an excellent introduction to Django's framework, showcasing how to set up models, views, and templates while also providing a hands-on experience for intermediate and professional developers. Let’s dive into the process step-by-step.
Setting Up Your Django Environment
Before we begin coding, it's essential to set up the development environment. Django requires Python, so ensure you have Python 3.6 or higher installed on your machine. You can check your Python version by running the following command in your terminal:
python --version
Next, install Django using pip, which is the package installer for Python:
pip install django
After installing Django, it's good practice to create a virtual environment to manage dependencies effectively. You can do this using the following commands:
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
With your virtual environment set up and activated, you can now proceed to create your Django project.
Creating the Project and App Structure
Create a new Django project named todo_app
:
django-admin startproject todo_app
Navigate into your project directory:
cd todo_app
Now, create a new Django app within your project called tasks
:
python manage.py startapp tasks
Your folder structure should now look like this:
todo_app/
manage.py
todo_app/
__init__.py
settings.py
urls.py
wsgi.py
tasks/
migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Next, add the tasks
app to your project's settings. Open settings.py
and add 'tasks'
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
...
'tasks',
]
Defining Models for Tasks and Categories
Models in Django define the structure of your database. For our To-Do List application, we need models for Task and Category. Open models.py
in the tasks
app and define the following:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
After creating your models, you need to run the following commands to create the database tables:
# Create migrations
python manage.py makemigrations
# Apply migrations
python manage.py migrate
To manage tasks effectively, you’ll need to create forms. Django provides a handy way to create forms using ModelForm
. In your tasks
app, create a new file named forms.py
and add the following code:
from django import forms
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ['title', 'description', 'category']
This form will allow users to input task details and select a category.
Implementing Views and URL Routing
Next, you need to create views to handle the business logic for your application. Open views.py
in the tasks
app and add the following code:
from django.shortcuts import render, redirect
from .models import Task, Category
from .forms import TaskForm
def task_list(request):
tasks = Task.objects.all()
return render(request, 'tasks/task_list.html', {'tasks': tasks})
def add_task(request):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('task_list')
else:
form = TaskForm()
return render(request, 'tasks/add_task.html', {'form': form})
Now, let’s define the URLs for these views. Open urls.py
in the tasks
app (create it if it doesn't exist) and add:
from django.urls import path
from . import views
urlpatterns = [
path('', views.task_list, name='task_list'),
path('add/', views.add_task, name='add_task'),
]
Next, include these URLs in your main urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tasks.urls')),
]
Designing the User Interface with Templates
To display your tasks and forms, you need to create templates. Create a folder named templates
inside the tasks
app, and within it, create another folder named tasks
. Inside this folder, create two HTML files: task_list.html
and add_task.html
.
task_list.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task List</title>
</head>
<body>
<h1>Your Tasks</h1>
<a href="{% url 'add_task' %}">Add New Task</a>
<ul>
{% for task in tasks %}
<li>{{ task.title }} - {{ task.completed|yesno:"Completed,Not Completed" }}</li>
{% endfor %}
</ul>
</body>
</html>
add_task.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Task</title>
</head>
<body>
<h1>Add a New Task</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Task</button>
</form>
</body>
</html>
Adding Functionality for Task Completion
To enhance your application, let’s add the ability to mark tasks as complete. Modify the Task
model to include a method that toggles the completion status:
def complete_task(request, task_id):
task = Task.objects.get(id=task_id)
task.completed = not task.completed
task.save()
return redirect('task_list')
Don’t forget to add the URL for this view in your tasks/urls.py
:
path('complete/<int:task_id>/', views.complete_task, name='complete_task'),
Now, update the task_list.html
to include a link to complete tasks:
<li>
{{ task.title }} - {{ task.completed|yesno:"Completed,Not Completed" }}
<a href="{% url 'complete_task' task.id %}">Toggle Completion</a>
</li>
Testing and Debugging the Application
Testing is a crucial part of the development process. Use Django's built-in testing framework to create tests for your application. Open tests.py
in your tasks
app and write tests for the models and views:
from django.test import TestCase
from .models import Task, Category
class TaskModelTest(TestCase):
def setUp(self):
self.category = Category.objects.create(name='Work')
self.task = Task.objects.create(title='Test Task', category=self.category)
def test_task_creation(self):
self.assertEqual(str(self.task), 'Test Task')
self.assertFalse(self.task.completed)
Run your tests using:
python manage.py test
Deploying Your To-Do List Application
Once your application is complete, it’s time to deploy it. You can use platforms like Heroku, DigitalOcean, or AWS for deployment. For Heroku, follow these steps:
Install the Heroku CLI and log in.
Create a requirements.txt
file:
pip freeze > requirements.txt
Create a Procfile
with the following content:
web: gunicorn todo_app.wsgi
Initialize a Git repository and push your code to Heroku:
git init
heroku create
git add .
git commit -m "Initial commit"
git push heroku master
Finally, run migrations on Heroku:
heroku run python manage.py migrate
Your To-Do List application is now live!
Summary
In this article, we explored the process of creating a simple To-Do List application using Django. From setting up your environment to deploying the application, we covered essential aspects such as model creation, form handling, view implementation, and testing.
This project not only enhances your Django skills but also provides a practical tool for managing tasks efficiently. Whether you're developing personal projects or enhancing your portfolio, building applications like this is invaluable for your growth as a developer.
Last Update: 28 Dec, 2024