Create a To - Do App with Django and Bootstrap

 To - Do App with Django

In this article, you will learn to create a awesome To-Do App with Django. You will get a step-wise guide to create the application with source code. Share the article if you like the content and it helps you in your coding journey. So, without wasting time, let's start with the project.



If you know the fundamentals of Python, Django and a little bit of HTML, CSS and Bootstrap, then you are good to go with this project.

Step 1 - Install Django

Let's start with the project. But we before we process make sure that you have installed Django in your system. 

To check whether Django is installed or not and which version is installed in your computer, open your command line (cmd) and write the below code and press enter.

python -m django --version

If Django is installed, you should see the version of your installation and if it isn't you will get a error.

If Django is not installed in your computer, open your command line (cmd) and write the below line and hit enter to install Django.

pip install django

If you are using Mac or Linus, write pip3 install django. Also, before running the above command make sure that your computer is connected to internet connection, Django will get automatically download and installed in your computer.

Also Read - Digital Clock with Pygame

Step 2 - Creating a new project

Open you command prompt in the folder where you want to keep the code of your project. To open command prompt, right click with shift pressed and you will get a option "open command window here" in the pop up.

Start the project by using following command:-

django-admin startproject todo

After executing the above command, you will find a folder "todo" created in the directory where you have opened the command prompt which contains some files. 

Also Read - Installing VS Code IDE and Python

Open this todo folder in your IDE. Inside the folder, we have the following files.

todo/
    manage.py
    todo/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Now, change the directory to todo folder, where your manage.py file is present. Now, let's run the project using following command.

python manage.py runserver

You will see the following output on command line.

Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

July 18, 2021 - 10:00:51
Django version 3.2, using settings 'todo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
You have started a Django development server written in Python. Now, server is running, visit http://127.0.0.1:8000/ with your web browser. You will see a congratulation page, with rocket as shown below.



This confirms that our Django project has been successfully created. Now, let's make it a To - Do App.


Step 3 - Create Template

Let's create a beautiful template for our to-do app using Bootstrap. For that first type the following command and hit enter.


mkdir templates
The above command will create a "templates" folder in outer todo folder.
Now, open templates folder in your IDE and create a todo.html file and paste the below code.


<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <title>To-do App</title>
  <style>
    .mybutton {
      float: right;
      border-radius: 8px;
      background: var(--bs-info);
      color: white;
      border: 2px solid #1099b5;
    }

    .mybutton:hover {
      background: #1cb7d6;
    }
  </style>
</head>

<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
      <a class="navbar-brand" href="/">To-do App</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="/">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" href="https://www.youtube.com/channel/UCOrK73JfFgjzvbQvFEiN9FQ">Youtube Channel</a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" href="http://iconicpython.blogspot.com/">My Website</a>
          </li>
        </ul>
        <form class="d-flex">
          <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-light btn-outline-dark" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>

  <div class="container mt-3">
    <form method="POST"> {% csrf_token %}
      <div class="input-group mb-3">
        <input style="height: 40px;" name='task' type="text" class="form-control" placeholder="Add Task"
          aria-label="Recipient's username" aria-describedby="button-addon2"></input>
        <button class="btn btn-outline-secondary" type="submit" id="button-addon2">Add</button>
      </div>
    </form>
  </div>

  <div class="container mt-3">
    {% for myindex, tasks in taskdict.items %}
    <div class="alert alert-info alert-dismissible fade show" role="alert">
      <strong>{{ tasks }}</strong>

      <form style="float: right; display: inline-flex; flex-direction: row;" action="/todo" method="POST"> {% csrf_token %}
        <button class='mybutton' name="removebtn" value='{{myindex}}' aria-label="Close">Remove</button>
      </form>
    </div>
    {% endfor %}



  </div>

  <!-- Optional JavaScript; choose one of the two! -->

  <!-- Option 1: Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
    crossorigin="anonymous"></script>

  <!-- Option 2: Separate Popper and Bootstrap JS -->
  <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
    -->
</body>

</html>

Step 4 - Edit settings.py

Now, we will edit settings.py file. We created a template and now let's add it to the templates in settings.py. Find TEMPLATES in settings.py and specify 'templates' folder in 'APP_DIRS'.


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Step 5 - Create Views.py

Now, create a views.py file inside the folder todo where you have other python files like settings.py, urls.py, etc. E
dit and paste the following code in it.


from django.http import HttpResponse
from django.shortcuts import render
tasklist = []

def todo(request):
    mytask = request.POST.get('task','')
    
    params = adhtml(request,mytask)    
    return render(request, 'todo.html', params)

def adhtml(request, mytask):
    remtask = request.POST.get('removebtn','yy')
    if mytask != "":
        if mytask not in tasklist:
            tasklist.append(mytask)

    if remtask != "yy":
        tasklist.pop(int(remtask))
        
    taskdict = {}
    for tindex, tasks in enumerate(tasklist):
            taskdict[tindex] = tasks
            
    params = {'taskdict': taskdict}
    return params

Step 6 - Edit urls.py

Till now we have created our template and written the code for view.py. Here's the code for urls.py


"""todo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("todo",views.todo, name="todo"),
]

Here we are done with writing all the source code. Now, let's run the code and check how is our To- Do App working. Write the following command to start server.


python manage.py runserver

After this, open the link http://127.0.0.1:8000/todo with your web browser and you will find a awesome To Do App in fully working condition with all functions of adding and deleting tasks in it. Here, is demo in the form of GIF of the To-Do App.





The purpose of the article was to give you step-wise source code to create a To-do App with Django. If you want detail explanation of each step done in the project, comment below.

If you like the article, share it among your friends, social media and various communities you are in. The project will work in your computer, if you have done all the work step by step.

Enjoy Coding!!


For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post