Building a To Do Application in Python using Django Framework – Part 06

In this 6th part all I want to do is to display the todo items, that I created through the admin panel, on the web page. It turns out to be actually very easy.

First of all we have to modify the view.py file, particularly the get_index() function. This is how my function looks like now:

from django.shortcuts import render
from .models import TodoItem

def get_todo_index(request):
    items = TodoItem.objects.all()
    return render(request, "todo/index.html", {'items': items})
    
def edit_todo_item(request, id):
    return render(request, "todo/edit.html")
    
def delete_todo_item(request, id):
    return render(request, "todo/delete.html")
    
def toggle_todo_item(request, id):
    return render(request, "todo/toggle.html")

Notice that I had to import from the models.py file the TodoItem model because I am going to use it in the function get_index().

In the function I defined a variable named items which represents the existing todo items, then I pass it to the render() function as a dictionary.

Next step would be the index.html file. It has to be modified so it would display the items. Here you have my index.html from todo folder:

{% extends 'home/base.html' %}

{% block content %}
    
    <div class="col-md-6 offset-md-3 p-5">
        {% for item in items %}
            <p><i class="fas fa-edit"></i> <i class="fas fa-toggle-on"></i> <i class="fas fa-trash-alt text-danger"></i> <span id="item-todo" class="pl-2 pt-1 pb-1 pr-5 m-5">{{ item.name }}</span></p><hr>
        {% endfor %}
    </div>
    
{% endblock content %}

This is it for the 6th part. In the 7th part we have to create a new file for the edit form and edit the view.py file.

Leave a Reply