How To Build a Todo Application With Django

How To Build a Todo Application With Django – A todo app is one of the applications that every developer should try to design because it covers all of the standard development patterns, such as:

  • Databases
  • Views
  • Templates

In this lesson, you’ll learn how to use Django to create a fully functional todo app. You’ll be able to perform the following tasks:

  • View the entire to-do list
  • Add a new to-do item to your list.
  • Update your to-do list.
  • Delete the item from your to-do list.

By the end of this tutorial, you will be able to perform the following tasks:]

  • Before you create a single line of code, plan out your project.
  • How to make a virtual reality environment.
  • How to set up a Django project on your own.
  • Relationships in the database are modelled.
  • Perform database operations like create, update, read, and delete.
  • Create a webpage with the data from the database.

Why Django?

Django is a Python high-level framework for creating complicated database-driven applications. Did you know that Django is used to power some of the most well-known websites, such as Instagram?

Prerequisites to Build a Todo Application With Django
  • Python3 should already be installed.
  • Python and Django basics are required.

Project Design

Before creating any code, think about what you want to build. This will save you a lot of time and headaches in the future. For instance, consider your database and ask yourself the following questions:

  • What will the structure of my database be?
  • What information do I need to record?
  • What characteristics does a to-do item possess?
  • What will the user interface resemble?

When working with Python projects, it’s always a good idea to set up a virtual environment to keep project dependencies separate from the rest of the system. Create a directory and use the following code to cd into it:

mkdir TODO
cd TODO

Using the venv module, create a virtual environment and activate it.

python3 -m venv env
source env/bin/activate

Using pip, install Django.

header ad
pip install Django

Make a new Django project with the name todoapp.

django-admin startproject todoapp

Create an app called tasks in the new todoapp directory, as seen below:

cd todoapp
django-admin startapp tasks

The following files will be created by Django for the project, and your directory should look like this:

How To Build a Todo Application With Django

As demonstrated below, add the tasks app to the list of installed apps in settings.py.

INSTALLED_APPS = [
.....
'tasks' #add this
]

Databases

SQLite, a lightweight database application, is included with Django. If you want to use a different database, you can do so by going to:

  • PostgreSQL
  • Mongo Db
  • Mysql, e.t.c

Models

Models represent the stuff you wish to store in your apps (todo items). Attributes are assigned to models. The model User, for example, can include properties like username, email, and so on.

Your database will only have one model in this tutorial i.e TaskItem

Add the following code to tasks/models:

from django.db import models
from django.utils import timezone


# Create your models here.

class TaskItem(models.Model):
    DEFAULT = 'DEFAULT'
    PERSONAL  =  'PERSONAL'
    SHOPPING = 'SHOPPING'
    WISHLIST = 'WISHLIST'
    WORK =' WORK'
    CATEGORIES = (
        (DEFAULT,DEFAULT),
        (PERSONAL,PERSONAL),
        (SHOPPING,SHOPPING),
        (WISHLIST,WISHLIST),
        (WORK,WORK)
    )
    title = models.CharField(max_length=100,blank=True,null=True)
    body =models.TextField(null= True,blank=True)
    due_date = models.DateField(default= timezone.now)
    task_finished = models.BooleanField(default= True)
    category = models. CharField(max_length= 20, choices= CATEGORIES , default= DEFAULT)

    def __str__(self):
        return f'{self.title}'

So, what exactly is going on in the code above? Let’s have a look at it in more detail.

  • To begin, create the TaskItem model, which has the title, body, due_data, and a boolean field that indicates whether or not the task has been completed.
  • The next step is to create a field category that accepts a list of options, such as default, personal, shopping, wishlist, and work.
  • Then there’s the _str_() method, which returns a “English-like” version of the model instance object.

Migrations

Running migrations have an impact on all modifications you make to your models. As a result, issue the migrations command.

python manage.py makemigrations
Migrations for 'tasks':
  tasks/migrations/0001_initial.py
    - Create model TaskItem

The migrate command follows, which creates the database tables.

python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, tasks
Running migrations:
  Applying tasks.0001_initial... OK

Django admin site

The Django admin site provides a robust interface for adding and managing data. The first step is to create a superuser who will have access to the admin interface and will be able to add and delete data.

python manage.py createsuperuser
Username (leave blank to use 'earth'): admin
Email address: 
Password: 
Password (again): 
Superuser created successfully

Then, in the admin app, register the models. Add the following code to the admin.py file:

from django.contrib import admin
from .models import TaskItem
# Register your models here.
admin.site.register(TaskItem)

Now start the development server and log in with the superuser credentials at http://127.0.0.1:8000/admin. This is what you should see:

You can now enter some data to work with.

Views and Templates

Django views send data to templates, which then display the data. The main benefit of Django is that it comes with built-in views that hide the majority of the underlying functionality of CRUD operations. That is precisely what you will do.

Class-based generic views

The first view will be a view that fetches all the Task items from the database. Open views.py and add the following code:

from django.shortcuts import redirect, render
from django.views.generic import ListView
from .models import TaskItem

# Create your views here.

class TodoItemListView(ListView):
    model = TaskItem
    template_name = 'tasks/todoitem_list.html'

A ListView is a general view that retrieves items from a list. The class will have two properties: model and template name, and it will conduct all of the necessary functionality to get all TaskItem objects from the database. The todoitem list.html template must now be created. By default, Django looks for templates in the templates directory, thus the file directory should adhere to the following convention:

tasks/ 
    templates/
           tasks/
            -task-list.html

Templating in Django

The view will offer a context (object list) through which the template will communicate. Curly braces will be used as a placeholder for data given by Django in the template. Add the following code to task-list.html:

{% block content%}
{% for task in object_list %}
<li>{{task.body}}</li>
<li>{{task.due_date}}</li>
<li>{{task.category}}</li>
{% endfor %}
{% endblock %}

URLs

Django will take a client’s request for a certain URL, transmit it to the URL resolver, and then match it against a list of patterns. If a match is detected, the information is forwarded to the appropriate view functions. As seen below, open urls.py and add a URL pattern that corresponds to the TodoItemListView we built earlier:

from django.contrib import admin
from django.urls import path
from tasks.views import TodoItemListView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('todo/list',TodoItemListView.as_view(),name ='todo_list'),
  
]

http://127.0.0.1:8000/tasks is the path to view all of the Todo items.

Forms

You’ve been adding to-do items using the admin interface so far. However, this is not the best option. To improve your online app, you must include forms. Django has ModelForm classes that make creating forms from model classes a breeze. In the tasks app, create a file called forms.py and add the following code:

from django import forms
from .models import TaskItem


class TaskItemCreateForm(forms.ModelForm):
    class Meta:
        model = TaskItem
        fields =('title', 'body','due_date','category')

For the fields defined above, the TaskItemCreate form will automatically produce form fields.

Create todo item

To accomplish this, you’ll continue to use Django’s built-in generic classes. Create a view for adding a new to-do item in views.py.

from django.shortcuts import redirect, render
from django.views.generic import ListView,CreateView
from .models import TaskItem
from .forms import TaskItemCreateForm

# Create your views here.

class TodoItemListView(ListView):
    model = TaskItem
    template_name = 'tasks/todoitem_list.html'

class TodoItemCreateView(CreateView):
    model  = TaskItem
    template_name ='tasks/todoitem_create_form.html'
    form_class  =TaskItemCreateForm
    success_url = '/todo/list'

The only difference between the first view and the CreateTodoItemView is that you’ve now included two more properties: a form class and a success_url. After successfully adding a new to-do item, a success_url specifies the route to which the user will be forwarded.

Add the following code to the todoitemcreate form.html template:

{% block content %}
<h2>Whats To Be Done ? Create Now</h2>
<form method="post">
<div>
  {% csrf_token %} {{ form.as_p }}
  <input type="submit" value="Submit" />
</div>
</form>
{% endblock %}

Make the following changes to the URL:

from django.contrib import admin
from django.urls import path
from tasks.views import TodoItemListView,TodoItemCreateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('todo/list',TodoItemListView.as_view(),name ='todo_list'),
    path('todo/create',TodoItemCreateView.as_view(),name ='create_list'),
]

Create a new to-do item by going to http://127.0.0.1:8000/todo/create.

How To Build a Todo Application With Django

Update and delete todo item

As can be seen from the endpoints above, generic classes provide the majority of the underlying functionality. You’ll add functionality for amending and deleting a to-do item in this area. You’ll apply what you’ve learnt, including the following:

  • Create a form from models
  • Create a view
  • Render the context data to an HTML page

Add a form for updating a to-do item to forms.py.

from django import forms
from .models import TaskItem

class TaskItemUpdateForm(forms.ModelForm):
    class Meta:
        model = TaskItem
        fields =('body','due_date','task_finished','category')

Only the fields mentioned in the Meta class need to be updated.
Create views for amending and deleting to-do items after that. The code is as follows:

from django.shortcuts import redirect, render
from django.views.generic import ListView,CreateView, UpdateView,DeleteView
from .models import TaskItem
from .forms import TaskItemCreateForm,TaskItemUpdateForm

# Create your views here.


class TodoItemUpdateView(UpdateView):
    model  = TaskItem
    template_name ='tasks/todoitem_update_form.html'
    form_class  =TaskItemUpdateForm
    success_url = '/todo/list'


class TodoItemDeleteView(DeleteView):
    model = TaskItem
    template_name = 'tasks/todoitem_delete_form.html'
    success_url = "/todo/list"

Create the corresponding templates : todoitem_update_form.html

{% block content %}
<h2>Edit To Do Item</h2>
<form method="post">
<div>
  {% csrf_token %} {{ form.as_p }}
  <input type="submit" value="Submit" />
</div>
</form>
{% endblock %}

todoitem_delete_form.html


{% block content %}
<h2>Delete To Do</h2>
<form method="post">
<div>
  {% csrf_token %}
  <p>Are you sure you want to delete "{{ object }}"?</p>
  <input type="submit" value="Confirm" />
</div>
</form>
{% endblock %}

URLS

Make the following changes to the url.py file:

from django.contrib import admin
from django.urls import path
from tasks.views import TodoItemListView,TodoItemCreateView,TodoItemUpdateView,TodoItemDeleteView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('todo/list',TodoItemListView.as_view(),name ='todo_list'),
    path('todo/create',TodoItemCreateView.as_view(),name ='create_list'),
    path('todo/update/<pk>',TodoItemUpdateView.as_view(),name ='update_list'),
    path('todo/delete/<pk>',TodoItemDeleteView.as_view(),name ='delete_list'),

]

The todo/update/pk> and todo/delete.pk> pathways fetch to-do items based on their primary keys. If you wish to update an instance with id ==1, for example, the path is http://127.0.0.1:8000/todo/update/1.

Go to http://127.0.0.1:8000/todo/delete/1 to delete a to-do item.

Conclusion – How To Build a Todo Application With Django

Your application can now do what it was designed to do: view, create, update, and delete to-do items.(How To Build a Todo Application With Django)

Reference:

Build a Todo Application With Django – betterprogramming.pub

Leave a Comment

Your email address will not be published.