top of page
Manisha Sahu

Todo App in Django

In this article, we are going to build a todo app using class-based views in Django in only 10 simple steps.
 

Run the below commands through cmd


Step-1

django-admin startproject Todo_ClassBasedView

Step-2

python manage.py startapp todo

Open this Project using any text editor for example-Sublime, Vscode, etc.


Step-3

In setting.py file of your Project i.e Todo_ClassBasedView add the name of your app.

INSTALLED_APPS = [       
  'todo',     
 'django.contrib.admin',
 -----------------
 ---------------]

Step-4

In urls.py file of Project, include the URL of the app. The urls.py file will look like this.

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

Step-5

In models.py file, add the following code to it. This will make a table by name Create, where we can store the title, date-time of the creation, and the status (i.e completed or not) of a task.

from django.db import models
from django.urls import reverse

# Create your models here.
class Create(models.Model):
    title=models.CharField(max_length=200,blank=False)
    complete = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
       return self.title
    
    def get_absolute_url(self):
       return reverse('index')  

Step-6

In admin.py file register, the table.

from .models import Create
admin.site.register(Create)  

Step-7

Now we have to do the migrations to save the changes we had made. Run this through cmd or by the terminal of your editor.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

U can verify the instance of your table is created or not using the admin panel.


Step-8

Make forms.py file inside the app folder and insert the following code.

from django import forms
from django.forms import ModelForm
from .models import *

class CreateForm(forms.ModelForm):
  title=forms.CharField(widget=forms.TextInput(attrs{'placeholder':'Add new task...'}))
  class Meta:
    model = Create
    fields = '__all__'

Step-9

Add the following code to views.py file. With the help of these functions, we can add, update, and delete our tasks.

from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import CreateForm
from django.views.generic import CreateView
from django.views.generic import ListView 
from .models import Create
from django.views.generic import UpdateView 
from django.views.generic import DeleteView

# Create your views here.

class index(CreateView):
       model = Create
       form_class=CreateForm
       template_name = "todo/index.html"
       
       def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context["objects"] = self.model.objects.all()
            return context

class update(UpdateView):
       model =Create
       template_name='todo/update.html'
       success_url="/"
       fields = {
          "title",
          "complete"
          }
          
class delete(DeleteView):
       model = Create
       success_url="/"
       template_name='todo/delete.html'

Now make index.html file inside templates/todo.

<!DOCTYPE html>
<html>
<head>
<title>Todo</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
input{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input::placeholder {
color:#85adad;
}
.submit{
background-color: #33cc33;
}
.center-column{
width:600px;
margin: 20px auto;
padding:20px;
background-color:#ffff99;
border-radius: 3px;
box-shadow: 6px 2px 30px 0px rgba(0,0,0,0.75);
}
.item-row{
background-color:#ff3399;
margin: 10px;
padding: 20px;
border-radius: 3p;
color: #fff;
font-size: 16px;
box-shadow: 0px -1px 10px -4px rgba(0,0,0,0.75);
}
.btn-danger{
background-color: #33cc33;
border-color: white;
}
.button{
background:#000099;
border-color:lightblue;
}
</style>
</head>
<body>
<div class="center-column">
<center><h3>Todo-list</h3></center>
<form action=" " method="POST">
{% csrf_token %}
{{form.title}}
<input class="btn btn-info button" type="submit" value="Create Task"></form>
<div class="todo-list">
{% for entry in objects %}
<!-- Blog Post -->
<div class="item-row">
<a class="btn btn-sm btn-info button" href="{% url 'update' entry.id %}">Update</a>
<a class="btn btn-sm btn-danger" href="{% url 'delete' entry.id %}">Delete</a>
{% if entry.complete == True %}
<strike>{{entry}}</strike>
{% else %}
<span>{{entry}}</span>
{% endif %}
</div>
{% endfor %}
</div>
 </div>   
 </body>
 </html>

The other two templates we have to make inside templates/todo are-


update.html

<!DOCTYPE html>
<html>
<head>
<title>Update</title>
</head>
<body>
<form method="post" action=" "> 
{% csrf_token %} 
{{ form.as_p }} 
<input type="submit" value="Save"> 
</form> 
</body>
</html>

delete.html

<!DOCTYPE html>
<html>
<head>
<title>Delete Task</title>
</head>
<body>
<form method="post" action=" ">
{% csrf_token %} 
<p>Are you sure you want to delete "{{ object }}"?</p> 
<input type="submit" value="Confirm"> 
</form>
</body>
</html>

Step-10

At last, we have to make urls.py file inside the app folder.

from .views import *
from django.urls import path

urlpatterns =[
  path('',index.as_view(),name="index"),
  path('<pk>/update',update.as_view(),name="update"),
  path('<pk>/delete',delete.as_view(),delete.as_view(),name="delete"),
  ]

 

Get the whole code here-


Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in the above code, or want some updates.

Follow Programmers Door for more.

89 views0 comments

Recent Posts

See All

Comments


bottom of page