Introduction

Creating a To-Do list app is a common project for learning web development. In this guide, we'll walk you through the process of building a To-Do list app with Flask, a Python web framework. You'll learn how to set up your Flask application, create routes for adding, updating, and deleting tasks, and display tasks to users. Let's get started!


Step 1: Setting Up Your Flask Application

Before you can build a To-Do list app, make sure you have a Flask application. If not, you can create a basic Flask app like this:

from flask import Flask, render_template, request, redirect
app = Flask(__name)

Step 2: Creating a Task Model

To represent tasks in your To-Do list, define a model. Here's an example of a simple model for a "Task" with a title and status:

class Task:
def __init__(self, title, status):
self.title = title
self.status = status

Step 3: Creating Routes

Create routes to handle adding, updating, and deleting tasks. Here's an example of a route to display the To-Do list:

tasks = []
@app.route('/')
def index():
return render_template('index.html', tasks=tasks)

Create HTML templates to display tasks.


Step 4: Creating HTML Templates

Create HTML templates for rendering the To-Do list. Here's an example of an "index.html" template:

<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>My To-Do List</h1>
<ul>
{% for task in tasks %}
<li>
<span>{{ task.title }}</span>
<a href="/update/{{ loop.index }}">Mark as Completed</a>
<a href="/delete/{{ loop.index }}">Delete</a>
</li>
{% endfor %}
</ul>
<form method="POST" action="/add">
<label for="task">New Task:</label>
<input type="text" id="task" name="task" required>
<input type="submit" value="Add Task">
</form>
</body>
</html>

Step 5: Handling Task Actions

Create routes to handle adding, updating, and deleting tasks. Here's an example route for adding a new task:

@app.route('/add', methods=['POST'])
def add_task():
task = request.form['task']
tasks.append(Task(task, False))
return redirect('/')

Create similar routes for updating and deleting tasks.


Step 6: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

if __name__ == '__main__':
app.run()

Now, you can run your application with the command python your_app.py and access your To-Do list app.


Conclusion

Building a To-Do list app with Flask is a great way to learn web development. You've learned how to set up your application, create routes, and interact with tasks. You can further enhance this project by adding features like task editing, task prioritization, and user accounts.