DEV Community

Blackie
Blackie

Posted on

Python Day 13: Creating a Simple Todo App with Django

Django is a powerful web framework that can be used to build web applications. In this article, we will walk through the process of creating a simple to-do list app using Django.

Image description

Step 1 Install Django: Firstly, let's install Django.

Open up the terminal and run the code below.

pip install django
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a new Django project: Once we've installed Django, we can create a new project by running the code below in the terminal.

django-admin startproject mytodo
Enter fullscreen mode Exit fullscreen mode

This will create a new directory called mytodo that contains the files and directories for our project.

Step 3. Create a new Django app:
Next, we'll need to create a new Django app for our to-do list.

To do this, let's navigate to mytodo directory by running the command in our terminal.

cd mytodo
Enter fullscreen mode Exit fullscreen mode

Next, run the code below to create our app.

python manage.py startapp todo
Enter fullscreen mode Exit fullscreen mode

This will create a new directory called todo that contains the files and directories for our app.

Step 4. Define to-do list model: A model is a representation of a database table in Django. We'll need to define a model for our to-do list that includes fields for the task name and a boolean field to indicate whether the task is complete. To do this, let's open up the models.py file in the todo directory and add the following code:

from django.db import models

class TodoItem(models.Model):
    text = models.CharField(max_length=200)
    complete = models.BooleanField(default=False)
Enter fullscreen mode Exit fullscreen mode

With code above we've created a new model called TodoItem with two fields: text and complete.

Step 5. Install the app: To use the todo app in our project, we'll need to add it to the INSTALLED_APPS list in the settings.py file in the mytodo directory. To do this, let's open up the settings.py file and add the following line to the INSTALLED_APPS list:

'todo.apps.TodoConfig',
Enter fullscreen mode Exit fullscreen mode

This will tell Django to include the todo app in our project.

Step 6. Run migrations: Once we've defined our model, we'll need to create the corresponding database table. To do this, we can run migrations.

To run migrations, run the code below in the terminal.

python manage.py makemigrations todo
Enter fullscreen mode Exit fullscreen mode

This will create a new migration file in the migrations directory in the todo app.

Then, let's run the code below to apply the migration and create the database table.

python manage.py migrate todo
Enter fullscreen mode Exit fullscreen mode

Step 7. Create views: A view is a function that takes a web request and returns a web response. We'll need to create two views for our to-do list: one to display the list of tasks and another to handle the form submission for adding a new task. To do this, let's open up the views.py file in the todo directory and add the following code:

from django.shortcuts import render, redirect, get_object_or_404
from .models import TodoItem

def todo_list(request):
    items = TodoItem.objects.all()
    return render(request, 'todo/todo_list.html', {'items': items})

def add_item(request):
    if request.method == 'POST':
        text = request.POST['text']
        TodoItem.objects.create(text=text)
        return redirect('todo_list')
    else:
        return render(request, 'todo/add_item.html')

def toggle_complete(request, item_id):
    item = get_object_or_404(TodoItem, id=item_id)
    item.complete = not item.complete
    item.save()
    return redirect('todo_list')

def delete_item(request, item_id):
    item = get_object_or_404(TodoItem, id=item_id)
    item.delete()
    return redirect('todo_list')
Enter fullscreen mode Exit fullscreen mode

This code defines four views: todo_list, add_item, toggle_complete, and delete_item.

Step 8. Create templates: A template is a file that defines the HTML structure of a web page.

We'll need to create two templates for our to-do list: one to display the list of tasks and another to handle the form submission for adding a new task. To do this, let's open up the todo directory and create a new directory called templates.

Inside the templates directory, let's create a new directory called todo. Inside the todo directory, let's create two new files: todo_list.html and add_item.html.

Hence, add the following code to todo_list.html:

<h1>My To-Do List</h1>

<form method="post" action="{% url 'add_item' %}">
    {% csrf_token %}
    <input type="text" name="text" placeholder="Add a new item">
    <button type="submit">Add</button>
</form>

<ul>
    {% for item in items %}
        <li>
            {{ item.text }}
            {% if item.complete %}
                (Completed)
            {% endif %}
            <form method="post" action="{% url 'toggle_complete' item.id %}">
                {% csrf_token %}
                <button type="submit">
                    {% if item.complete %}
                        Mark as Incomplete
                    {% else %}
                        Mark as Complete
                    {% endif %}
                </button>
            </form>
            <form method="post" action="{% url 'delete_item' item.id %}">
                {% csrf_token %}
                <button type="submit">Delete</button>
            </form>
        </li>
    {% endfor %}
</ul>

Enter fullscreen mode Exit fullscreen mode

And add the following code to add_item.html:

<h1>Add a New To-Do Item</h1>

<form method="post">
    {% csrf_token %}
    <label for="text">Text:</label>
    <input type="text" name="text" id="text">
    <button type="submit">Add</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Step 9. Update URLs: Finally, we'll need to update our URLs to map to the views we've created. To do this, let's open up the urls.py file in the mytodo directory and add the following code:

from django.urls import path
from todo.views import todo_list, add_item, toggle_complete, delete_item

urlpatterns = [
    path('', todo_list, name='todo_list'),
    path('add/', add_item, name='add_item'),
    path('toggle_complete/<int:item_id>/', toggle_complete, name='toggle_complete'),
    path('delete/<int:item_id>/', delete_item, name='delete_item'),
]
Enter fullscreen mode Exit fullscreen mode

This code maps the URLs to the views we've created.

And that's it! Now we have a working app. Run the code in the terminal.

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

We can then access our app by navigating to http://127.0.0.1:8000/ in the web browser.

Top comments (0)