Create Your Own To-Do List Flask App Using Python: Step-by-Step Guide with Source Code Included! – 2024

Hey guys, In this article, I will guide you through the process of coding a to-do list Flask App in Python. Whether you’re a beginner or an experienced programmer, this step-by-step tutorial will help you build a functional to-do list that can boost your productivity. So let’s dive right in!

Checkout the video here – https://youtu.be/wFBCXqCm5-M

Sneak Peek at our Final To-Do List Flask Application

To do list flask app main screen
To-do list flask app

Understanding the Concept of a To-Do List

Before we start coding, let’s take a moment to understand the concept of a to-do list. A to-do list is a simple list of tasks or activities that need to be completed. It acts as a reminder and helps us stay organized by providing a clear overview of our pending tasks.

Benefits of Using a To-Do List

Using a to-do list offers several benefits:

  • Improved productivity: A to-do list helps you prioritize tasks, ensuring that you focus on the most important ones first.
  • Reduced stress: By organizing your tasks, you can alleviate the stress of remembering everything and avoid missing deadlines.
  • Increased efficiency: A well-maintained to-do list allows you to work efficiently and complete tasks more quickly.
  • Better time management: By scheduling tasks and setting deadlines, you can effectively manage your time and meet your goals.

Functions of our To-Do List

This program allows you to perform the following actions:

Adding Tasks to the To-do List

  • To add a task to the To-do list, type the new task and hit the Add Task Button.

Remove a task from the To-do List by specifying its index

  • To remove a task from the To-do List, select hit the Delete button in front of that Task.
delete a task in To-do list flask app in python

Clear the entire To-do List

  • To clear the To-do List, simply click on the Clear List Button and it will clear the List.
clear list in To-do list flask app in python

Future Scope for To-do List Flask App in Python

You can customize the program further or add additional functionality based on your requirements. Following are some of the advancements you can do in your program:

  • You can also use Databases to store tasks along with some more features like start date, deadline, etc.
  • You can also incorporate an Alarm system.

Code for To-do list Flask App in Python

app.py

# to-do list flask app

import os
from flask import Flask,request,render_template
from datetime import date

#### Defining Flask App
app = Flask(__name__)


#### Saving Date today in 2 different formats
datetoday = date.today().strftime("%m_%d_%y")
datetoday2 = date.today().strftime("%d-%B-%Y")


#### If this file doesn't exist, create it
if 'tasks.txt' not in os.listdir('.'):
    with open('tasks.txt','w') as f:
        f.write('')


def gettasklist():
    with open('tasks.txt','r') as f:
        tasklist = f.readlines()
    return tasklist

def createnewtasklist():
    os.remove('tasks.txt')
    with open('tasks.txt','w') as f:
        f.write('')

def updatetasklist(tasklist):
    os.remove('tasks.txt')
    with open('tasks.txt','w') as f:
        f.writelines(tasklist)


################## ROUTING FUNCTIONS #########################

#### Our main page
@app.route('/')
def home():
    return render_template('home.html',datetoday2=datetoday2,tasklist=gettasklist(),l=len(gettasklist())) 


# Function to clear the to-do list
@app.route('/clear')
def clear_list():
    createnewtasklist()
    return render_template('home.html',datetoday2=datetoday2,tasklist=gettasklist(),l=len(gettasklist())) 


# Function to add a task to the to-do list
@app.route('/addtask',methods=['POST'])
def add_task():
    task = request.form.get('newtask')
    with open('tasks.txt','a') as f:
        f.writelines(task+'\n')
    return render_template('home.html',datetoday2=datetoday2,tasklist=gettasklist(),l=len(gettasklist())) 


# Function to remove a task from the to-do list
@app.route('/deltask',methods=['GET'])
def remove_task():
    task_index = int(request.args.get('deltaskid'))
    tasklist = gettasklist()
    print(task_index)
    print(tasklist)
    if task_index < 0 or task_index > len(tasklist):
        return render_template('home.html',datetoday2=datetoday2,tasklist=tasklist,l=len(tasklist),mess='Invalid Index...') 
    else:
        removed_task = tasklist.pop(task_index)
    updatetasklist(tasklist)
    return render_template('home.html',datetoday2=datetoday2,tasklist=tasklist,l=len(tasklist)) 
    


#### Our main function which runs the Flask App
if __name__ == '__main__':
    app.run(debug=True)

home.html

Create a folder called templates and create a file inside that called ‘home.html’. The final folder structure should look like the below:

to-do list flask app in python folder structure
<!doctype html>
<html lang="en">

<style type='text/css'>
    * {
        padding: 0;
        margin: 0;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }


    body {
        background-image: url('https://cutewallpaper.org/21/1920-x-1080-gif/1920x1080-Wallpapercartoon-Wallpapers-Driverlayer-Search-.gif');
        background-size: cover;
        font-family: sans-serif;
        margin-top: 40px;
        height: 100vh;
        padding: 0;
        margin: 0;
    }

    table {
        border: 1px;
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 86%;
        margin: auto;
    }

    td,
    th {
        border: 1px solid black !important;
        padding: 5px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
</style>


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>To-Do List</title>
</head>

<body>

    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">To-Do List
            </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 ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/"><b>Home</b></a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>


    <div class='mt-1 text-center'>
        <h1 style="width: auto;margin: auto;color: white;padding: 11px;font-size: 44px;">To-Do List</h1>
    </div>

    <div class='mt-3 text-center'>
        <h3 style="font-size: 22px;color:beige;">{{ datetoday2 }} | <span id="clock"></span></h3>
    </div>

    {% if mess%}
    <p class="text-center" style="color: red;font-size: 20px;">{{ mess }}</p>
    {% endif %}

    <div class="row text-center" style="padding: 20px;margin: 20px;">

        <div class="col"
            style="border-radius: 20px;padding: 0px;background-color:rgb(211,211,211,0.5);margin:0px 10px 10px 10px;min-height: 400px;">
            <h2 style="border-radius: 20px 20px 0px 0px;background-color: #0b4c61;color: white;padding: 10px;">Task
                List <i class="material-icons">assignment</i></h2>
            <a style="text-decoration: none;max-width: 300px;" href="/clear">
                <button style="font-size: 24px;font-weight: bold;border-radius: 10px;width: 250px;margin-bottom: 10px;"
                    type='submit' class='btn btn-danger'>Clear List</button>
            </a>
            <table style="background-color: white;">
                <tr>
                    <td><b>S No</b></td>
                    <td><b>Task</b></td>
                    <td><b>Action</b></td>
                </tr>
                {% if l %}

                {% for i in range(l) %}
                <tr>
                    <td>{{ i+1 }}</td>
                    <td>{{ tasklist[i] }}</td>
                    <td><a href="/deltask?deltaskid={{i}}"><button type='submit'
                                class='btn btn-danger'>Delete</button></a></td>
                </tr>
                {% endfor %}
                {% endif %}
            </table>

        </div>

        <div class="col"
            style="border-radius: 20px;padding: 0px;background-color:rgb(211,211,211,0.5);margin:0px 10px 10px 10px;height: 400px;">
            <form action='/addtask' method="POST" enctype="multipart/form-data">
                <h2 style="border-radius: 20px 20px 0px 0px;background-color: #0b4c61;color: white;padding: 10px;">Add
                    New Task <i class="material-icons">control_point_duplicate</i></h2>
                <label style="font-size: 20px;"><b>Enter New Task*</b></label>
                <br>
                <input type="text" id="newtask" name='newtask'
                    style="font-size: 20px;margin-top:10px;margin-bottom:10px;"
                    required>
                <br>
                <button style="width: 232px;margin-top: 20px;font-size: 20px;" type='submit' class='btn btn-dark'>Add
                    Task
                </button>
                <br>
            </form>
        </div>

    </div>

    <script type="text/javascript">
        var clockElement = document.getElementById('clock');

        function clock() {
            clockElement.textContent = new Date().toString().slice(15, 24);
        }

        setInterval(clock, 1000);
    </script>

</body>

</html>

Video tutorial

Download Source Code

Conclusion

Congratulations! You have successfully coded a to-do list flask app in Python. By following this tutorial, you’ve learned how to show a to-do list, add tasks to the to-do list, remove tasks from the to-do list, and clear the to-do list. With your new Python skills, you can now create personalized to-do lists to stay organized and improve your productivity.

So this is how you can code a To-do list flask app in Python. If you have any doubt regarding this, you can contact me by mail.

FAQs

Q1: Can I run this to-do list application on any operating system?

Yes, Python is a cross-platform language, so you can run this application on Windows, macOS, or Linux.

Q2: Is it possible to share the to-do list with others?

The basic implementation we covered in this article is for personal use. However, you can extend the application’s functionality to allow for sharing and collaboration by utilizing databases or cloud-based services.

Q3: Can I customize the UI of the to-do list application?

Absolutely! The UI design is highly customizable. You can modify the colors, fonts, and layout to suit your preferences.

Q4: Are there any limitations to the number of tasks I can add?

The number of tasks you can add to your to-do list depends on the available memory on your device. However, you can optimize the application to handle a large number of tasks efficiently.

Q5: Can I integrate this application with other tools or services?

Q5: Can I integrate this application with other tools or services? Certainly! Python offers various libraries and APIs that allow for seamless integration with other tools and services. You can connect your to-do list application with calendars, email services, or project management platforms to enhance its functionality.

Read my last article – Create your first web app using Flask

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net

Leave a Reply

Your email address will not be published. Required fields are marked *