Building a Task Manager: From Concept to Completion

November 27, 2024, 11:09 am
Python
Python
DevelopmentHomeInterestITLearn
Location: United States
Employees: 10001+
SQLite Home Page
Location: United States, North Carolina, Charlotte
Employees: 11-50
Founded date: 2000
Creating a task manager application is like planting a seed and nurturing it into a flourishing tree. Each step, from setup to deployment, is crucial for growth. This guide will walk you through the process of building a task manager using Python and Flask, ensuring you have a solid foundation for your project.

Setting the Stage


Before diving into code, ensure you have the right tools. Python 3 and Git are essential. Python serves as the backbone of your application, while Git manages your code versions. If you don’t have Python installed, download it from the official site.

Next, create a virtual environment. This isolates your project dependencies, preventing conflicts with other projects. Open your terminal and execute the following commands:

```bash
mkdir task_manager
cd task_manager
python3 -m venv venv
```

Activate the virtual environment:

- On macOS/Linux:
```bash
source venv/bin/activate
```

- On Windows:
```bash
venv\Scripts\activate
```

You should see `(venv)` at the beginning of your command line, indicating that the virtual environment is active.

Installing Dependencies


With the virtual environment active, install the necessary libraries:

```bash
pip install flask flask_sqlalchemy
```

Flask is your web framework, while Flask_SQLAlchemy simplifies database interactions.

Project Structure


Organizing your project is like laying a solid foundation for a house. Here’s how your directory should look:

```
task_manager/
├── app.py
├── models.py
├── extensions.py
├── templates/
│ ├── index.html
│ └── update.html
└── static/
├── style.css
└── timer.js
```

-

app.py

: The heart of your application.
-

models.py

: Where you define your database models.
-

extensions.py

: Initializes Flask extensions.
-

templates/

: Contains HTML files.
-

static/

: Houses CSS and JavaScript files.

Database Initialization


In `extensions.py`, initialize your database:

```python
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
```

Defining Models


In `models.py`, define the `Task` model. This represents a task in your application:

```python
from extensions import db
from datetime import datetime

class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Boolean, default=False)
deadline = db.Column(db.DateTime, nullable=True)

def __repr__(self):
return f''
```

Setting Up the Application


Now, configure your Flask application in `app.py`:

```python
from flask import Flask, render_template, request, redirect, url_for
from extensions import db
from models import Task
from datetime import datetime
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
```

Creating Routes


Routes are the pathways of your application. They define how users interact with it. Here’s how to set up the main route and task management functionalities:

```python
@app.route('/')
@app.route('/')
def index(filter='all'):
if filter == 'completed':
tasks = Task.query.filter_by(completed=True).all()
elif filter == 'pending':
tasks = Task.query.filter_by(completed=False).all()
else:
tasks = Task.query.all()
return render_template('index.html', tasks=tasks)

@app.route('/add', methods=['POST'])
def add_task():
task_content = request.form['content']
date_str = request.form.get('date')
time_str = request.form.get('time')
deadline = None
if date_str and time_str:
deadline_str = f"{date_str} {time_str}"
deadline = datetime.strptime(deadline_str, '%d.%m.%Y %H:%M')
new_task = Task(content=task_content, deadline=deadline)
db.session.add(new_task)
db.session.commit()
return redirect(url_for('index'))

@app.route('/delete/')
def delete_task(id):
task = Task.query.get_or_404(id)
db.session.delete(task)
db.session.commit()
return redirect(url_for('index'))

@app.route('/complete/')
def complete_task(id):
task = Task.query.get_or_404(id)
task.completed = not task.completed
db.session.commit()
return redirect(url_for('index'))

@app.route('/update/', methods=['GET', 'POST'])
def update_task(id):
task = Task.query.get_or_404(id)
if request.method == 'POST':
task.content = request.form['content']
date_str = request.form.get('date')
time_str = request.form.get('time')
if date_str and time_str:
deadline_str = f"{date_str} {time_str}"
task.deadline = datetime.strptime(deadline_str, '%d.%m.%Y %H:%M')
else:
task.deadline = None
db.session.commit()
return redirect(url_for('index'))
return render_template('update.html', task=task)

if __name__ == "__main__":
with app.app_context():
if not os.path.exists('tasks.db'):
db.create_all()
app.run(debug=True)
```

Creating Templates


Your application needs a face. Create `index.html` for the main page:

```html




Task Manager




Task Manager












```

And create `update.html` for editing tasks:

```html




Update Task


Update Task








Back to Task List


```

Styling Your Application


In `static/style.css`, add styles to make your application visually appealing. Here’s a simple example:

```css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}

.container {
max-width: 600px;
margin: auto;
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
text-align: center;
}

form {
margin-bottom: 20px;
}

input {
width: calc(100% - 22px);
padding: 10px;
margin: 5px 0;
}

button {
padding: 10px;
background-color: #5cb85c;
color: white;
border: none;
cursor: pointer;
}

button:hover {
background-color: #4cae4c;
}

ul {
list-style: none;
padding: 0;
}

li {
background: #f9f9f9;
padding: 10px;
margin: 5px 0;
border-radius: 5px;
}
```

Final Touches


With everything in place, run your application:

```bash
python app.py
```

Visit `http://localhost:5000` in your browser. You should see your task manager in action.

Conclusion


Building a task manager is a rewarding journey. Each step is a building block, creating a robust application. From setting up your environment to deploying your app, every detail matters. With this guide, you have the tools to grow your own digital garden. Now, go forth and cultivate your ideas!