To-Do Lists Using Python and Django

Khilesh
9 min readMay 13, 2022

Hey guys, in this article I will teach you how to create a to-do list in python using Django. As in this article, we are focusing mainly on the backend part i.e Django, so our website will not look so attractive but that works fine. In the todo list, you will have crud functionality i.e. create, retrieve, update and delete. And I expect that Django is already installed on your pc.

Prerequisite:

  1. Basic Python and Django knowledge are necessary.
  2. Basic HTML

Create a Django project

Django provides a command that allows us to create an initial project file structure. To create a Django project, open your desired folder with vs code or any other code editor (I use vs code) and enter the given command as mentioned below :

django-admin startproject todoproject

Congratulations, you created your first Django project. Now, open this todoproject folder in vs code.

You will see a lot of files there on the left-hand side: __init__.py, asgi.py,settings.py,urls.py, and wsgi.py. Initially, you don’t have to worry about these files. There are only two files inside todoproject that are important for your app:

  1. settings.py: This indicates settings and configuration for your project and contains initial default settings.
  2. urls.py: This is the place where your URL patterns live. Each URL defined here is mapped to a view.

After creating your first project you have to create your app inside your project folder. Basically, an app interacts with a framework to provide some specific functionalities. To create an app write the command

python manage.py startapp todoapp

You can create your project and app with any name.

Your folder and subfolders should look like this :

TODOPROJECT/

├── todoapp/

├── todoproject/

And your todoapp folder should look like this :

todoapp/

├── migrations/
│ └── __init__.py

├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py

Activating the Application:

In order for Django to keep track of your application, you have to activate it. To do this edit your settings.py file of your todoproject and add a todo to the INSTALLED_APPS setting. It should look like this:

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"todoapp",
]

Now save the file settings.py and close it. Or you can click on the file option on vs code navbar and you will see the Auto save option. Click it and whenever you make any changes in your directory it will be automatically saved.

And now you have to modify another file of todoproject i.e. urls.py and this should look like this

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("todoapp.urls")),
]

The lines that are written in bold format, should be added in urls.py.

The new URL pattern defined with include refers to URL patterns that we are going to define in our todoapp application.

Now create the urls.py file in your todoapp application. And write the code as written below :

from django.urls import path
from .import views
urlpatterns = [
path("",views.index,name='index'),
]

Here we are importing views from our current folder i.e. todoapp. And inside our urlpatterns, we import the index function from the views file of todoapp. name=’index’ will helps us to refer to it in HTML templates which we will discuss shortly.

We have now completed our working project and app setup, but it doesn’t do much yet. You can test your work so far by starting the Django development server:

python manage.py runserver

Now you’ve finished testing, you can type Ctrl+C in the console window(terminal) to stop the server.

Designing the ToDo Data schema :

In this step, we’ll design the application model. Then we’ll use Django’s object-relational modeling(ORM) tools to map that data model into database tables.

Open the file models.py file in your editor which is present in todoapp. And add the following lines of code to it

from django.db import models# Create your models here.class Task(models.Model):
title = models.CharField(max_length=100)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

The file models.py defines your entire data model. In it, you’ve defined one function and one data model class:

We have declared title field inside our Task model class. And each title is limited to one hundred characters only.

complete field takes the boolean value as specified Booleanfield. We will have a checkbox like a button for this, if checked(true) then do something and if not(false) do something.

created field indicates when the post was created. Since we specify auto_now_add, the date will be saved automatically when creating an object.

__str__() method is the default human-readable representation of the object.

Creating the Database

Write the code as written below in the console window(terminal).

python manage.py makemigrations todoapp

then,

python manage.py migrate

With makemigrations, we’re telling Django that we’ve changed the application’s data model, and we’d like to record those changes. And on the other hand, With the migrate command, we put those changes into effect by running commands against the database.

Adding models to the administration site

Edit the admin.py file of the todoapp application and make it look like this :

from django.contrib import admin
from .models import Task

admin.site.register(Task)

We have imported our Task model from the models file and registered it to the admin site using admin. site.register(Task).

Creating a superuser

Do you know what’s the benefit of using Django as a backend tool? Django provides us with a built-in admin interface that is very useful for editing content and saves a lot of time. We can access the admin site by creating a superuser which is like registering ourselves there and we can manage the database. To create a superuser write the code as mentioned below:

python manage.py createsuperuser

You will see the following output as enter your desired username, email, and password. By the way, you don’t need to specify everything at the development phase just add admin as username name and password. It will not affect anything as you are working on your localhost.

Now run the server using python manage.py runserver and open a web browser and go to the address http://127.0.0.1:8000/admin/ . You will encounter with admin app’s login screen. Enter your credentials, which you provided while creating a superuser and the admin landing page appears:

Start a To-Do List

At the left of the main Django administration page, click on TASKS. On the next screen, click on the button at the top right that says ADD TASK.

A new form appears:

Fill the form with some random data. Give your TASK the title “Django Tutorial by khilesh” Then hit SAVE.

And that’s it, you just created your one item with the admin interface.

Creating a Modelform

Django ModelForm is a class that is used to directly convert a model into a Django form. If we’re building a database-driven app, chances are we’ll have forms that map closely to Django models. So instead of creating a redundant code to first create a form and then map it to the model in a view, we can directly use ModelForm. So, to create a modelform, create a forms.py file in the todoapp application and copy the code as given below:

from django import forms
from django.forms import ModelForm
from .models import *
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = "__all__"

Here we are using Django ModelForm, and we imported everything from the models file. Inside our Meta class, we specify the name of our model and the fields we require in our form. For example; if you have a model with name, address, roll no, and dob but if you want only name and roll no on the form then you can specify the name, and roll no in fields.

Creating the Django Views

Basically, this is the most important part of the todo project or we can say, we will write our all logic here i.e. how to create, update, retrieve and delete the task from the database.

In your editor, open the file todoapp/views.py.Create your view:

from django.shortcuts import render , redirect
from .models import Task
from .forms import TaskForm
#This index function is for creating and retrieving the data
def index(request):
1) tasks = Task.objects.all()
2) form = TaskForm()
3) if request.method =="POST":
4) form = TaskForm(request.POST)
5) if form.is_valid():
6) form.save()
7) return redirect('/')
8) context = {
9) 'tasks':tasks ,
10) 'form':form
11) }
12) return render(request,'index.html',context)
13)# This edit function is for editing our data14)def edit(request,id):
15) task = Task.objects.get(id=id)
16) form = TaskForm(instance=task)
17) if request.method=='POST':
18) form = TaskForm(request.POST , instance=task)
19) if form.is_valid():
20) form.save()
21) return redirect('/')
22) context = {
23) 'form':form
24) }
25) return render(request,'edit.html',context)
26) # This delete function is for deleting our data27)def delete(request,id):
28) item = Task.objects.get(id=id)
29) if request.method=='POST':
30) item.delete()
31) return redirect('/')
32) context ={
33) 'item':item
34) }
35) return render(request,'delete.html',context)

In this code, we are importing our Task model and our TaskForm. The index is our first view where we will create and retrieve data. In line 1 we are getting our objects from the Task model. In line 2 we are initializing our model form. Line 3 specifies that if someone fills the form then the POST method should run and the following command starts executing. We stored that Task form data in the form variable and checked whether the form is valid or not, if it is valid return to the homepage(‘/’) or else return to the same page. the context is created so that we can retrieve our data from the database to our templates(HTML ) and show it on the front.

Edit is our second view function where we are going to edit our created content/data. We specified an id in the argument so that we can edit the data according to the id number and if the data is valid it will be saved.

Delete is our 3rd view function where we are deleting our existing data using id. We use the delete method to delete the data.

Creating Templates

Basically, templates define how the data is displayed; they are usually written in HTML in combination with the Django template language. So, let’s create our templates. And remember that your templates folder should be inside your todoapp application. And create index.html, edit.html, and delete.html files inside the templates folder.

Now inside your index.html paste this code

<h3>Hey Bro, I'm doing django </h3>
<form method="POST" action='/'>
{% csrf_token %}
{{form.title}}
<input type="submit" name='Create task'>
</form>
{% for task in tasks %}
<div class="container">
{% if task.complete == True %}
<strike>{{task}}</strike>
{% else %}
<span>{{task}}</span>
{% endif %}
<a href ="{% url 'edit' task.id %} ">Edit</a>
<a href ="{% url 'delete' task.id %} ">Delete</a>
</div>
{% endfor %}

Here, we used {% csrf_token %}, this tag introduces a hidden field with an autogenerated token to avoid cross-site request forgery(CSRF) attacks. These attacks consist of a malicious website or program performing an unwanted action. The remaining is simple for loop, where the task is like ‘i’ we used to loop question and tasks is from the context which we specified earlier.

Now create an edit.html file, this will be reloaded when edit button is clicked from index.html.

<h3> Edit The List </h3>
<form method="POST" action="">
{% csrf_token %}
{{form}}
<input type="submit" name="Edit Task">
</form>

Now create a delete.html file, this will be reloaded when the delete button is clicked from index.html.

<h3>Are you really going to delete "{{item}}"</h3>
<a href ="{%url 'index'%}">Cancel</a>
<form action="" method="post">
{% csrf_token %}
<input type="submit" name='Confirm'>
</form>

Now Building a Request Handler

Open your urls.py file of the todoapp application and edit it. It should look like this ;

from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
path('edit/<str:id>/',views.edit,name='edit'),
path('delete/<str:id>/',views.delete,name='delete')
]

The final output should look like this:

I know guys, this doesn't look attractive but we just created our 1st backend website. Now if you wanna go further ahead you can add CSS to it, to make it more attractive. And please make sure the indentations is correct.

Thanks for reading💖

Follow me for more such content.

--

--

Khilesh

As someone who loves talking about spiritual topics and learning new things, I am always seeking personal growth and exploring new perspectives.