Make a simple Todo List App using Django

Aravind Kumar Vemula
6 min readDec 31, 2020

Lets try to build a simple todo list app using Django.

This will help you to install Django and creating a project.

Basic Intro of Django

Django is a Python-based free and open-source web framework that follows the model-template-views architectural pattern.

Lets install Django

  • Try this command to install Django, if you have no need to install it again.
pip install django
  • after installing, Lets start creating a project.
django-admin startproejct <ProjectName>
  • This will create your a project, in your project dir you will see a manage.py file, this is used to execute and run your project.
  • Lets start running the server.
python manage.py runserver
  • This will run your project on the port:8000 and open a new Webpage with the Url that will load a default page of Django that says this is successfully running
  • Now start creating a App.
python manage.py startapp <App_Name>
  • Lets name it has TodoList.
  • Now open a VsCode or any editor and open your project folder, here you will see two directories are created one is your Project dirand other is your App dir . You can create as much apps you can but under only one project directory.
  • Lets go to MainProject dir and search for settings.py and scroll down to INSTALLED_APPS and add your App name there.
INSTALLED_APPS = [
'TodoList', # this should be your app name
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
  • Now under your App dir go to views.py and create a new function and also import the HttpResponse.
from django.http import HttpResponsedef index(request):
return HttpResponse("Hello World!")
  • Now create a urls.py in App dir.
from django.urls import path
from . import views
app_name = "TodoList" # keep any name or app name
urlpatterns=[
path("",views.index,name="index")
]
  • Open urls.py in MainProject dir and add your App path.
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls), # this is default route path
path('Todolist/', include("TodoList.urls")) # this is routing to your app
]
  • Here include("TodoList.urls") this is used to go to your App and to urls.py and run your default page present in urls.py called index or anything.
  • Now again start your server. python manage.py runserver
  • Now you will see a text that says Hello World!, which is return from index function using HttpResponse.
  • Lets Start creating a Html file. There is structure to follow for creating the html, css, js files.
  • Html Structure:
  • template / New Folder Name / FileName.html
  • Css and Js file Structure:
  • static / New Folder Name /styles.css or /styles.js
  • After creating a Html file and some default html template code with some title and h1 tag with Todo List text.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Todo List</title>
</head>
<body>
<h1>Todo List</h1>
</body>
</html>
  • Now go to urls.py file in app dir, add render method to render your Html file to a web page .
def index(request):
return render(request,"Todolist/index.html")
  • This start your server and go to url and add :8000/Todolist this will take you to html page of Todolist file and it will show you a Todo List text with huge font-size.
  • The todo list will be in the form of List of details.
  • Lets render some default list details to Web Browser. Now go to views.py in your app dir, create a global variable for list with random data in it.
task = ["foo","bar","baz"]
  • Now under views.py file go to index function add a context this is a third parameter of render method, this will be in the form of key-value pair.
return render(request,"Todolist/index.html",{
"tasks":task # your List name
})
  • Now under index.html file write a default code for un-orderlist (ul) with list of data (li)
<ul>
<li> task1 </li>
<li> task2 </li>
<li> task3 </li>
<li> task4 </li>
</ul>
  • This is a default code but when we using Django framework we can add looping conditions, conditional statements and etc.. in Html file. For using this we need to add {{}} this in our html file to access variables or making some conditons. Eg:
<body>
<h1>Hello {{Name}}</h1> # here Name is variable
</body>
  • Lets try to render list in html page. For this we use for loop for loop every element in list and render it out.
<ul>
{% for task in tasks %}
<li>{{task}}</li>
{% endfor %}
</ul>
  • This will be the output.
  • Now Lets add form to the page, where we can new data to the list.
  • Under the views.py in your App dir, add the import statements.
from django.http import HttpResponseRedirect
from django import forms
from django.urls import reverse
  • Lets create a new class called NewTextFormwith parameter (forms.Form) and create a CharField text input with a label.
class NewTextForm(forms.Form):
tasks = forms.CharField(label="New Task:") # forms.CharField will create you a new text input
  • Now in index funtion add new key-value pair in context of render called form with the NewTextForm class.
return render(request,"Todolist/index.html",{
"tasks":task,
"form":NewTextForm(),
})
  • Now in index.html file you can access this form using {{ form }} and lets first create a form in html file with method equal to POST and form to it with.
<form method="POST">
{{form}}
<button type="submit" name="button">Submit</button>
</form>
  • It will show you like:
  • When to type anything and submit it. It will show you a message like CSRF verification failed. Request aborted.
  • To solve this problem add {% csrf_token %} in the form.
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit" name="button">Submit</button>
</form>
  • This will create you a unique id for each user when they open the page and try to submit the form. The Django middleware checks the id matches to the csrf_token then the form will be submitted.
  • When it submitted it should be added to the task list, to added follow the process.
  • In views.py under index function
def index(request):
if request.method == "POST":
form = NewTextForm(request.POST)
if form.is_valid():
tasks = form.cleaned_data["tasks"]
task.append(tasks)
return HttpResponseRedirect(reverse("todolist:index"))
return render(request,"Todolist/index.html",{
"tasks":task,
"form":NewTextForm(),
})
  • Here when we hit submit. it will check weather the method is GET or POST, if it is POST add the parameter request.POST to NEWTEXTFORM class this will store the value of text input as assign to form. Check the form is valid or not, if it valid make a cleaned_data of form and take the tasks text input from it. and append to the tasks list.
  • For each form there should be a action prop this will tell after submit where to redirect.
<form action="{% url 'todolist:index' %}" method="POST">
{% csrf_token %}
{{form}}
<button type="submit" name="button">Submit</button>
</form>
  • Here TodoList:index TodoList is app_name where we created in urls.py file which will tell you go to index function ( in views.py )and return the related html file or TodoList:profile tell to go to profile function and return the related html file.
  • Now Lets empty the List in views.py called tasks = [].
  • Now run the server and you will get like.
  • Lets insert some data to it.

Thanks for Reading the Article!

For adding styles to the page Follow me and check for upcoming Story in adding Styles to Django App.

Enjoy Playing with it!

Follow me in Github, Twitter, Linkedin.

--

--

Aravind Kumar Vemula
Aravind Kumar Vemula

Written by Aravind Kumar Vemula

Full Stack Developer [Web | Mobile]

No responses yet