Building a To-Do List App in Django - A Comprehensive Guide
Introduction
Creating a To-Do List app is a great way to learn Django and build a practical web application. In this comprehensive guide, we'll walk through the process of building a To-Do List app using Django. You'll learn how to set up the project, create models for tasks, build views and templates, and implement features such as adding, updating, and deleting tasks.
Prerequisites
Before you begin, make sure you have the following prerequisites in place:
- Django Installed: Ensure you have Django installed. You can install it using pip.
- Python Knowledge: Basic knowledge of Python programming is essential.
- HTML and CSS: Familiarity with HTML and CSS is recommended for building templates.
Step 1: Creating a Django Project
First, create a Django project to serve as the foundation for your To-Do List app.
Sample Project Creation
Use the following Django command to create a new project:
django-admin startproject todo_list_project
Step 2: Creating a To-Do List App
Within your Django project, create a new app specifically for the To-Do List functionality.
Sample App Creation
Use the following Django command to create a new app:
python manage.py startapp todo_list
Step 3: Creating Models
Define models for your tasks in the To-Do List. You might have a model for tasks, each with a title and completion status.
Sample Task Model
Create a model in your app's models.py file:
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
Step 4: Building Views and Templates
Create views and templates for your To-Do List app. You'll need views for listing tasks, adding tasks, updating tasks, and deleting tasks.
Sample View and Template
Create a view and its corresponding template for listing tasks:
from django.shortcuts import render
from .models import Task
def task_list(request):
tasks = Task.objects.all()
return render(request, 'todo_list/task_list.html', {'tasks': tasks})
Step 5: Implementing Features
Implement features such as adding, updating, and deleting tasks. You'll need views and templates for these actions.
Sample View for Adding a Task
Create a view and template for adding tasks:
def add_task(request):
if request.method == 'POST':
title = request.POST['title']
Task.objects.create(title=title)
return redirect('task_list')
return render(request, 'todo_list/add_task.html')
Conclusion
Building a To-Do List app in Django is a practical way to apply your Django skills and create a useful web application. This guide provides the knowledge and sample code to help you get started on your To-Do List project.