Here's a step-by-step guide to creating a basic Flask project with a functional Todo app. This project includes features for adding, updating, and deleting todo items, as well as a SQLite database for storage.
Project Structure :
flask_todo/
│
├── app.py
├── project.db
├── templates/
│ └── todos.html
└── static/
└── styles.css
├── app.py
├── project.db
├── templates/
│ └── todos.html
└── static/
└── styles.css
Step 1: Set Up Your Environment
Install Flask:
pip install Flask Flask-SQLAlchemy
Create the Project Structure: Create the folders and files as shown above.
Step 2: Create the app.py File
This file contains the main Flask application logic.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
# Initialize Flask app
app = Flask(__name__)
# Configuring the SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///project.db'
# Initialize SQLAlchemy with the app
db = SQLAlchemy(app)
# Define the Todo model
class Todo(db.Model):
sno = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=False)
desc = db.Column(db.String(200), nullable=False)
def __repr__(self) -> str:
return f"ID: {self.sno}, Title: {self.title}, Description: {self.desc}"
# Home route (handles adding new Todos)
@app.route('/', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
# Retrieve form data
title = request.form['title']
desc = request.form['desc']
# Create a new Todo item with the submitted form data
todo = Todo(title=title, desc=desc)
db.session.add(todo)
db.session.commit()
return redirect(url_for('show_todos'))
return redirect(url_for('show_todos'))
# Route to show todos
@app.route('/todos')
def show_todos():
todos = Todo.query.all() # Fetch all Todo items from the database
return render_template('todos.html', todos=todos)
# Route to delete a todo item
@app.route('/delete/<int:sno>')
def delete(sno):
todo = Todo.query.filter_by(sno=sno).first()
if todo:
db.session.delete(todo)
db.session.commit()
return redirect(url_for('show_todos'))
# Route to update a todo item
@app.route('/update/<int:sno>', methods=['GET', 'POST'])
def update(sno):
todo = Todo.query.filter_by(sno=sno).first()
if request.method == 'POST':
# Update todo details
todo.title = request.form['title']
todo.desc = request.form['desc']
db.session.commit()
return redirect(url_for('show_todos'))
todos = Todo.query.all()
return render_template('todos.html', todos=todos, todo_to_update=todo)
# Ensure tables are created and the app runs correctly
if __name__ == '__main__':
with app.app_context():
db.create_all()
# Start the Flask app
app.run(debug=True)
Step 3: Create the todos.html Template
This HTML file will serve as the front end for the Todo application.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo List</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Todo List</h1>
<!-- Add Todo Form -->
<form action="/" method="POST">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<label for="desc">Description:</label>
<input type="text" id="desc" name="desc" required>
<button type="submit">Add Todo</button>
</form>
<!-- Todo List with Update and Delete actions -->
<h2>Your Todos</h2>
<ul>
{% for todo in todos %}
<li>
<span>{{ todo.title }}: {{ todo.desc }}</span>
<!-- Update and Delete buttons -->
<span>
<a href="/update/{{ todo.sno }}">Update</a>
<a href="/delete/{{ todo.sno }}" style="color: red;">Delete</a>
</span>
</li>
{% endfor %}
</ul>
{% if todo_to_update %}
<h2>Update Todo</h2>
<!-- Update Todo Form -->
<form action="/update/{{ todo_to_update.sno }}" method="POST">
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="{{ todo_to_update.title }}" required>
<label for="desc">Description:</label>
<input type="text" id="desc" name="desc" value="{{ todo_to_update.desc }}" required>
<button type="submit">Update Todo</button>
</form>
{% endif %}
</body>
</html>
Step 4: Create the CSS File styles.css
Add some styling to your application.
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1, h2 {
color: #333;
}
form {
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 15px;
background: #28a745;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #218838;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background: #fff;
padding: 10px;
margin: 10px 0;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
a {
text-decoration: none;
color: #007bff;
margin-left: 10px;
}
a:hover {
text-decoration: underline;
}
Step 5: Run Your Application
Make sure you’re in the project directory.
Run the Flask application:
python app.py
Step 6: Access the Application
Open your web browser and go to http://127.0.0.1:5000/ to see your Todo app in action.
Additional Features
You can enhance this basic application by adding:
User authentication.
Validation for the input fields.
More styling and layout improvements.
Pagination for the todo list if it grows large.
0 Comments