Welcome to our blog! Today, we’re embarking on an exciting journey to build a fundamental yet incredibly useful application: a To-Do List app. We’ll be using Django, a popular and powerful Python web framework, to bring this idea to life. Don’t worry if you’re new to web development or Django; we’ll break down each step with clear explanations and aim to make it as accessible as possible.
What is Django?
Before we dive into coding, let’s briefly introduce Django.
- Web Framework: Think of a framework as a pre-built structure or a set of tools and guidelines that helps you build web applications faster and more efficiently. Django provides many ready-made components, so you don’t have to build everything from scratch.
- Python-Based: Django is written in Python, a widely loved programming language known for its readability and versatility. If you know a bit of Python, you’ll feel right at home.
- “Batteries-Included”: This is a common phrase used to describe Django. It means Django comes with many essential features built-in, such as an administration panel, an Object-Relational Mapper (ORM) for database interaction, and more.
Why a To-Do List App?
The To-Do List app is a classic for a reason. It teaches us core concepts of web development:
- Data Management: Storing, retrieving, and updating information (your tasks!).
- User Interface: How users interact with the application through web pages.
- Backend Logic: The “brains” of the app that processes requests and manages data.
Setting Up Your Development Environment
To start building, you’ll need a few things on your computer.
1. Python Installation
If you don’t have Python installed, head over to the official Python website (python.org) and download the latest stable version for your operating system. During installation, make sure to check the box that says “Add Python to PATH.” This makes it easier to run Python commands from your terminal.
2. Virtual Environment
A virtual environment is like a separate, isolated workspace for your Python projects. It prevents different projects from interfering with each other’s dependencies (the libraries and packages they need).
To create one, open your terminal or command prompt and navigate to where you want to create your project. Then, run:
python -m venv myenv
python -m venv: This command tells Python to run thevenvmodule, which is used for creating virtual environments.myenv: This is the name we’re giving to our virtual environment. You can choose any name you like.
After creating it, you need to activate it.
On Windows:
.\myenv\Scripts\activate
On macOS/Linux:
source myenv/bin/activate
You’ll see the name of your virtual environment in parentheses at the beginning of your terminal prompt, indicating it’s active.
3. Installing Django
With your virtual environment activated, you can now install Django using pip, the Python package installer.
pip install django
This command downloads and installs the latest version of Django and its dependencies into your active virtual environment.
Creating Your First Django Project
Now, let’s create the basic structure for our To-Do List project.
Navigate to the directory where you want your project to live (outside of your myenv folder) and run:
django-admin startproject todolist_project
django-admin: This is a command-line utility that comes with Django.startproject todolist_project: This command creates a new Django project namedtodolist_project. It sets up a directory structure with essential configuration files.
Now, let’s move into our new project directory:
cd todolist_project
Inside this todolist_project directory, you’ll find another directory with the same name (todolist_project) and a manage.py file.
manage.py: This is another command-line utility that helps you interact with your Django project. You’ll use it for running your development server, creating database tables, and more.
Creating a Django App for Our To-Dos
Django projects are made up of “apps.” An app is a self-contained module that performs a specific function. For our To-Do List, we’ll create a todos app.
With your terminal still inside the todolist_project directory (where manage.py is located), run:
python manage.py startapp todos
This creates a new todos directory inside your project, containing files like models.py, views.py, and urls.py, which we’ll discuss shortly.
Configuring Our Project to Use the App
We need to tell our todolist_project that it now has a todos app. Open the settings.py file located inside the todolist_project folder (the one inside the outer todolist_project directory). Find the INSTALLED_APPS list and add 'todos' to it:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todos', # Add this line
]
Defining Our To-Do Item (The Model)
Now, let’s define what a “To-Do” item looks like in our database. Open todos/models.py and add the following code:
from django.db import models
class Todo(models.Model):
task = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.task
Let’s break this down:
from django.db import models: This line imports the necessary modules from Django’s database layer.class Todo(models.Model):: We’re defining a new Python class calledTodothat inherits frommodels.Model. This tells Django that this class represents a table in our database.task = models.CharField(max_length=200): This defines a field namedtask.CharFieldmeans it will store text, andmax_length=200specifies that the text can be up to 200 characters long.completed = models.BooleanField(default=False): This defines a field namedcompleted.BooleanFieldmeans it will store eitherTrueorFalse.default=Falsemeans that when a new To-Do item is created, it will automatically be marked as not completed.def __str__(self):: This is a special Python method that defines how an object of this class should be represented as a string. In our case, it will simply return thetasktext. This is very helpful for display purposes.
Creating and Applying Database Migrations
Django uses a system called “migrations” to manage changes to your database schema (the structure of your tables). When you create a new model like Todo, you need to create and apply these migrations.
In your terminal, from the todolist_project directory, run:
python manage.py makemigrations
This command detects the changes in your models and creates new migration files. You’ll see output indicating that a new migration file has been created for the todos app.
Next, apply these migrations to your database:
python manage.py migrate
This command runs the migration files and creates the actual tables in your database. Django uses an SQLite database by default, which is a simple file-based database that’s great for development.
Running the Development Server
To see our app in action, we need to run Django’s built-in development server.
python manage.py runserver
You should see output indicating that the server is running, usually at http://127.0.0.1:8000/. Open your web browser and go to this address. You’ll see a welcome page from Django, confirming that your project is set up correctly.
Displaying Our To-Do Items (Views and URLs)
Now, let’s create the logic to fetch our To-Do items and display them on a web page.
1. Views (todos/views.py)
Views are Python functions or classes that handle requests from users and return responses. Open todos/views.py and add the following:
from django.shortcuts import render
from .models import Todo
def todo_list(request):
todos = Todo.objects.all()
return render(request, 'todos/todo_list.html', {'todos': todos})
from django.shortcuts import render: This imports therendershortcut, which helps us render HTML templates.from .models import Todo: We import ourTodomodel so we can interact with the database.def todo_list(request):: This defines our view function. It takes anrequestobject as an argument.todos = Todo.objects.all(): This is a Django ORM query.Todo.objectsis a manager for theTodomodel, and.all()fetches allTodoobjects from the database.return render(request, 'todos/todo_list.html', {'todos': todos}): This renders an HTML template.request: The incoming HTTP request.'todos/todo_list.html': The path to the HTML template we’ll create.{'todos': todos}: A context dictionary. This passes our fetchedtodosto the template so we can use them there.
2. URLs (todos/urls.py and todolist_project/urls.py)
URLs are like addresses on our website. We need to map a URL to our todo_list view.
First, create a new file named urls.py inside your todos directory.
from django.urls import path
from . import views
urlpatterns = [
path('', views.todo_list, name='todo_list'),
]
from django.urls import path: Imports thepathfunction to define URL patterns.from . import views: Imports theviewsmodule from the current app.urlpatterns = [...]: This is a list of URL patterns for this app.path('', views.todo_list, name='todo_list'): This defines a URL pattern.'': An empty string means this pattern matches the root URL of this app (e.g.,/todos/).views.todo_list: Specifies that requests matching this pattern should be handled by thetodo_listview.name='todo_list': Gives this URL pattern a name, which is useful for reversing URLs in templates or other parts of the code.
Now, we need to tell our main project’s urls.py file to include the URLs from our todos app. Open todolist_project/urls.py:
from django.contrib import admin
from django.urls import path, include # Add 'include'
urlpatterns = [
path('admin/', admin.site.urls),
path('todos/', include('todos.urls')), # Add this line
]
path('todos/', include('todos.urls')): This line tells Django that any URL starting with/todos/should be handled by the URL patterns defined in ourtodosapp’surls.py.
Creating the HTML Template (todos/templates/todos/todo_list.html)
Finally, we need to create the HTML file that will display our To-Do items. Django looks for templates in a templates directory.
Create a new directory structure within your todos app: todos/templates/todos/. Inside this todos directory, create a file named todo_list.html.
<!-- todos/templates/todos/todo_list.html -->
<!DOCTYPE html>
<html>
<head>
<title>My To-Do List</title>
</head>
<body>
<h1>My To-Do List</h1>
<ul>
{% for todo in todos %}
<li>{{ todo.task }} - {% if todo.completed %}Completed{% else %}Pending{% endif %}</li>
{% endfor %}
</ul>
</body>
</html>
{% for todo in todos %}and{% endfor %}: These are Django template tags that loop through thetodoslist passed from our view.{{ todo.task }}: This is a Django template variable. It displays thetaskattribute of the currenttodoitem.{% if todo.completed %}...{% else %}...{% endif %}: Another template tag for conditional logic. It displays “Completed” iftodo.completedisTrue, and “Pending” otherwise.
Testing Your To-Do List App
Save all your files, make sure your development server is running (python manage.py runserver), and navigate to http://127.0.0.1:8000/todos/ in your browser.
You should see a heading “My To-Do List” and an empty unordered list. This is because we haven’t added any To-Do items yet!
Adding Items to the Database (The Easy Way: Django Admin)
Django’s built-in admin panel is an incredibly powerful tool for managing your application’s data without writing extra code.
First, we need to create a superuser (an administrator account):
python manage.py createsuperuser
Follow the prompts to create a username, email (optional), and password.
Now, restart your development server (python manage.py runserver). Go to http://127.0.0.1:8000/admin/ in your browser. Log in with the superuser credentials you just created.
You’ll see the Django administration site. You should also see “Todos” listed under “Your app’s models.” Click on “Todos.”
You’ll be able to add new To-Do items by clicking “Add todo” and filling in the “Task” field. You can also mark them as “Completed.”
Save your new To-Do item(s). Now, go back to http://127.0.0.1:8000/todos/. You should see your added To-Do items listed on the page!
Next Steps and Further Enhancements
This is just the beginning! You can extend this app in many ways:
- Adding New Tasks: Implement a form to allow users to add new tasks directly through the website.
- Editing Tasks: Allow users to edit existing tasks.
- Deleting Tasks: Provide a way to remove tasks from the list.
- Styling: Make your To-Do list look nicer with CSS.
- User Authentication: Allow different users to have their own To-Do lists.
Building this simple To-Do list app provides a solid foundation for understanding how web applications are built with Django. Keep exploring, keep experimenting, and happy coding!
Leave a Reply
You must be logged in to post a comment.