Display data on Index Page
On our index page now, we will be displaying all the data that has been stored in our data table. We will be using ‘Profile.query.all()‘ to query all the objects of the Profile class and then use Jinja templating language to display it dynamically on our index HTML file.
Update your index file as follows. The delete function will be written later on in this article. For now, we will query all the data from the data table and display it on our home page.
<!DOCTYPE html>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h3>Profiles</h3>
<a href="/add_data">ADD</a>
<br>
<table>
<thead>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>#</th>
</thead>
{% for data in profiles %}
<tbody>
<td>{{data.id}}</td>
<td>{{data.first_name}}</td>
<td>{{data.last_name}}</td>
<td>{{data.age}}</td>
<td><a href="/delete/{{data.id}}" type="button">Delete</a></td>
</tbody>
{% endfor%}
</table>
</body>
</html>
We loop through every object in profiles that we pass down to our template in our index function and print all its data in a tabular form. The index function in our app.py is updated as follows.
@app.route('/')
def index():
# Query all data and then pass it to the template
profiles = Profile.query.all()
return render_template('index.html', profiles=profiles)
Flask and Sqlalchemy Tutorial for Database
Flask is a micro web framework written in python. Micro-framework is normally a framework with little to no dependencies on external libraries. Though being a micro framework almost everything can be implemented using python libraries and other dependencies when and as required.
Table of Content
- Installing Flask
- Creating app.py
- Setting Up SQLAlchemy
- Creating Models
- Creating the database
- Making Migrations in database
- Creating the Index Page Of the Application
- Creating HTML page for form
- Function to add data using the form to the database
- Display data on Index Page
- Deleting data from our database
In this article, we will be building a Flask application that takes data in a form from the user and then displays it on another page on the website. We can also delete the data. We won’t focus on the front-end part rather we will be just coding the backend for the web application.