Creating a To-Do list with Django.

Creating a To-Do list with Django.

·

6 min read

Before we begin I'd recommend going through Getting started with Django.

Are you looking to build a simple to-do list app using Django? In this tutorial, I'll guide you through the process of building a basic to-do list web app using Django.

Prerequisites

Before we get started, make sure you have the following installed:

  • Python 3

  • Django

If you don't have Django installed, you can install it using the following command:

pip install django

Creating a new Django project

Let's start by creating a new Django project. Open up your terminal and navigate to the directory where you'd like to create your project. Then, run the following command:

django-admin startproject todoapp

This will create a new directory called todoapp with the basic structure of a Django project.

Creating a new Django app

Next, let's create a new Django app within our project. A Django app is a module that contains models, views, and templates for specific functionality within a project.

In your terminal, navigate to the todoapp directory and run the following command:

python manage.py startapp todo

This will create a new directory called todo with the basic structure of a Django app.

Defining a model for the to-do list item

In Django, a model is a Python class that maps to a database table. We'll use a model to define the schema for our to-do list items.

In the todo/models.py file, define a Todo class as follows:

from django.db import models

class Todo(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

In this model, we define two fields: a title field, which is a CharField with a maximum length of 200 characters, and a completed field, which is a BooleanField with a default value of False.

We also define a __str__ method, which is used to display the title of the to-do item in the Django admin interface.

Creating a view for displaying the to-do list

Now, we'll create a view to display the list of to-do items.

In the todo/views.py file, define a todo_list view as follows:

from django.shortcuts import render, redirect
from django import forms
from .models import Todo

class NewForm(forms.Form):
    title=forms.CharField(max_length=55)

# Create your views here.

def index(request):
    todo=Todo.objects.all()
    form=NewForm()
    if request.method=="POST":
        form=NewForm(request.POST)
        if form.is_valid():
            todo=Todo(title=form.cleaned_data["title"])
            todo.save()
        return redirect('index')
    context={'todos':todo, 'form':form}
    return render(request, 'todo_list.html', context)


def delete_todo(request, todo_id):
    todo = Todo.objects.get(id=todo_id)
    todo.delete()
    return redirect('index')

In this view, we retrieve all the to-do items from the database using the Todo.objects.all() method, and we create a new instance of the TodoForm class.

If the request method is POST, we create a new instance of TodoForm with the submitted data. If the form is valid, we save the form data to the database using the form.save() method. we create a context dictionary with the todos and form variables, and we render the todo_list.html template with this context.

Finally, to handle the delete request we created the delete_todo function.

Creating a template for displaying the to-do list

Now, we'll create a template to display the list of to-do items.

In the todo/templates directory, create a new file called todo_list.html and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TO-do list </title>
</head>
<body>
    <h1>Todo List</h1>

    <form method="POST" action="{% url 'index' %}">
        {% csrf_token %}
        {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Add</button>
    </form>

    <ul>
        {% for todo in todos %}
    <li>{{ todo.title }}</li>

    <form method="POST" action="{% url 'todo_delete' todo.id %}">
            {% csrf_token %}
            <button type="submit">delete</button>
        </form>
        {% endfor %}
    </ul>

</body>
</html>

In this template, we first display a form that allows the user to add a new to-do item. We use the form.as_p method to render the form fields as paragraphs.

We then display the list of to-do items using a for loop. For each item, we display the title and a delete button. The delete button is inside a form that has a POST method and an action attribute that specifies the URL for the todo_delete view (which we'll create in the next step). We also include a CSRF token for security.

Creating a URL pattern for the to-do list app

Finally, we need to create a URL pattern to map requests to the to-do list app to the appropriate views.

In the todo/urls.py file, add the following code:

from django.urls import path
from . import views

urlpatterns=[
    path('', views.index, name='index'),
    path('delete_todo/<int:todo_id>', views.delete_todo, name='todo_delete'),
]

This code tells Django that when a user visits the root URL (http://localhost:8000/), it should call the index view function in the views.py file.

In this URL pattern, we map the root URL to the index view, and we define a URL pattern for deleting to-do list items that includes the primary key of the item to be deleted.

Now we need to include the to-do list app's URL configuration in the main urls.py file in the project directory.

In the todoapp/urls.py file, add the following code:

# todoapp/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('todo.urls')),
    path('admin/', admin.site.urls),
]

This code includes the urls.py file from the todo app when a user visits the root URL (http://localhost:8000/). We also include the URL for the admin site, which is automatically included when we create a new Django project.

Registering the to-do list app in the Django project

Finally, we need to register the to-do list app in the Django project.

In the todoapp/settings.py file, add 'todo' to the INSTALLED_APPS list:

# todoapp/settings.py

INSTALLED_APPS = [
    # ...
    'todo',
]

This tells Django to include the todo app in the project.

That's it! With these configurations, the to-do list app should be accessible at http://localhost:8000/.

Running the to-do list app

We're now ready to run the to-do list app!

From the command line, run:

python manage.py runserver

This will start the development server.

Open your web browser and go to http://localhost:8000/. You should see the to-do list app.

You can add new to-do items, and delete them by clicking the "Delete" button next to each item.

Conclusion

In this tutorial, we've created a basic to-do list app in Django. We've used Django's built-in Model-View-Template architecture to create views and templates for displaying the to-do list items, and we've used Django's built-in form handling to allow users to add new items to the list. We've also added the ability to delete items using a delete button associated with each item.

There's a lot more that can be done to improve this app. For example, we could add more fields to the Todo model, such as a description or a due date. We could also add user authentication to allow each user to have their own to-do list. But for now, we have a simple, functional to-do list app that can be used as a starting point for more advanced projects.

I hope you found this tutorial helpful! If you have any questions or suggestions for future tutorials, please let me know.

P.S. : All the code can be found here.