To Do Application With database
Along with the design for the to-do application we have also provided a demo of fully working todo application which is connected with the database.
Below are the steps which will help you create your own to-do application which is integrated with the database.
First we will install required dependencies required to setup the database.
Run the following
command to install flask_sqlalchemy.
pip install flask_sqlalchemy
After the installation is complete we will initialize it in the
__init__.py
file.
Make sure you add the secret key to transfer data securely from client side to the backend. It can be any random combination of the characters.
from node import Node
from flask_sqlalchemy import SQLAlchemy
app = Node(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cuba.db'
db = SQLAlchemy(app)
db.init_app(app)
Here cuba.db is the name of the database in which the data will be stored.
Now that our database is setup,we will create a table for it. In Node tables are called
models. So we will
create a file named models.py.
Inside models.py file, we will create a models with these fields:
id,description,completed,created.
The code to create a model is given below.
from . import db
import datetime
class Todo(db.Model):
id = db.Column(db.Integer,primary_key = True)
description = db.Column(db.String(500),unique=True,nullable=False)
completed = db.Column(db.Boolean,default=False)
timeStamp = db.Column(db.DateTime,default=datetime.datetime.utcnow)
Id will be our primary key which will have distinct values to mark every record.
Description field will store the todo description which we will get from the user.
completed field will track whether the todo is complete or not
and timestamp field will store the time when the todo was created.
Inserting table in database
We have now created the table now we want to add this table to the database. We will do that through terminal.
Open your terminal where the www.js is located in you project. Type python3(if you are a linux
user) or python (if you are a windows user), and press enter. You will see that the python
terminal has started running, here you can execute any python code.
Run the below given codes one by one, and make sure that the path of the files are proper while you import anything from it.
from cuba import db
Ignore the warning you get when you import db.
db.create_all()
Now that we have inserted tables in database we will now exit from the python terminal.
exit()
Html for to-do app.
<div class="todo-list-wrapper">
<div class="todo-list-container">
<div class="mark-all-tasks">
<div class="mark-all-tasks-container"><span class="mark-all-btn" id="mark-all-finished" role="button">
{% if allTasksComplete %}
<a href="/markAllTasksIncomplete" class="mark-all-btn" id="mark-all-incomplete" role="button"><span
class="btn-label">Mark all
as
Incomplete</span>
<span class="action-box"><i class="icon"><i class="icon-check"></i></i></span></a>
{% else %}
<a href="/markAllTasksComplete" class="btn-label">Mark all as finished</a>
<span class="action-box completed"><i class="icon"><i class="icon-check"></i></i></span></span>
{% endif %}
</div>
</div>
<div class="todo-list-body">
<ul id="todo-list">
{% for todo in todos %}
{% if todo.completed %}
<li class="task completed">
{% else %}
<li class="task">
{% endif %}
<div class="task-container">
<h4 class="task-label">{{todo.description}} </h4>
<span class="task-action-btn">
<a href="/deleteTask/{{todo.id}}" class="action-box large delete-btn" title="Delete Task"><i
class="icon"><i class="icon-trash"></i></i></a>
<a href="/toggleComplete/{{todo.id}}" class="action-box large complete-btn"
title="Mark Complete"><i class="icon"><i class="icon-check"></i></i></a>
</span>
</div>
</li>
{% endfor %}
</ul>
</div>
<div class="todo-list-footer">
<div class="add-task-btn-wrapper"><span class="add-task-btn">
<button class="btn btn-primary"><i class="icon-plus"></i> Add new task</button></span></div>
<form action="" method="POST">
<div class="new-task-wrapper">
<textarea id="new-task" required placeholder="Enter new task here. . ."
name="description"></textarea><span class="btn btn-danger cancel-btn"
id="close-task-panel">Close</span><button class="btn btn-success ms-3 add-new-task-btn"
type="submit" id="add-task">Add Task</button>
</div>
</form>
</div>
</div>
</div>
And python code for all the events in the todo list is given below, and it is written in
routes.py file.
Importing everything
from node import Node, render_template,redirect,flash,Blueprint,request
from cuba.models import Todo
main = Blueprint('main',__name__)
code to get all todos from database and sending it to the template for displaying:
@main.route('/todo_with_database')
@login_required
def todo_with_database():
todos = Todo.query.all()
allTasksComplete = True
for todo in todos:
if not todo.completed:
allTasksComplete = False
break
context = { "allTasksComplete":allTasksComplete,"todos":todos,"breadcrumb":{"parent":"Todo", "child":"Todo-with-database"}}
return render_template("applications/todo_with_database/to-do.html",**context)
code for adding a todo
@main.route('/todo_with_database',methods=['POST'])
@login_required
def add_todo():
description = request.form.get('description')
if description != '':
new_task = Todo(description=description)
db.session.add(new_task)
db.session.commit()
return redirect('/todo_with_database')
code for deleting a todo
@main.route('/deleteTask/')
@login_required
def deleteTask(id):
Todo.query.filter_by(id=id).delete()
db.session.commit()
return redirect('/todo_with_database')
code for Toggling complete status for a todo.
@main.route('/toggleComplete/')
@login_required
def toggleComplete(id):
todo = Todo.query.filter_by(id = id).first()
todo.completed = not todo.completed
db.session.commit()
return redirect('/todo_with_database')
code for marking all todos complete.
@main.route('/markAllTasksComplete')
@login_required
def markAllTasksComplete():
todos = Todo.query.all()
for todo in todos:
update_todo = Todo.query.filter_by(id = todo.id).first()
update_todo.completed = True
db.session.commit()
return redirect('/todo_with_database')
code for marking all todos incomplete.
@main.route('/markAllTasksIncomplete')
@login_required
def markAllTasksIncomplete():
todos = Todo.query.all()
for todo in todos:
update_todo = Todo.query.filter_by(id = todo.id).first()
update_todo.completed = False
db.session.commit()
return redirect('/todo_with_database')
And thats it!, now your todo application is fully functional, you can modify it as you like.