Introduction
Bootstrap is a popular open-source front-end web development framework that helps developers create responsive websites. It contains a collection of HTML, CSS, and javascript components used to make web development easier. In this tutorial, we will be looking at how to add Bootstrap to your Flask app.
Table of Contents
Install modules
To begin we will first need to install Flask which will be our web server. To install Flask run the command below.
pip3 install Flask
File structure
Now let’s create a folder called flask-bootstrap and inside create a folder called templates and insert a file called index.html.
Import modules
Now let’s create a file called app.py inside the flask-bootstrap and import the modules below.
from flask import Flask, render_template
Initialize our app
Let’s initialize our application by adding the code below.
app = Flask(__name__)
Create a basic view
Now let’s create a basic view to render a basic HTML template.
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Add Bootstrap to the template
Inside the index.html template we created above add the code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<main>
<div class="d-flex justify-content-center align-items-center" style="height:100vh">
<form class="bg-light p-4" method="POST">
<h1 class="text-center">Login</h1>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter your username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter your password">
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</main>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
The above code begins by integrating bootstrap into our template by using a CDN which is the most reliable method since it’s fast and takes less space.
Run
Let’s now run our application, to do so open your terminal and run the command below.
python3 app.py
Results
Now after running the command above successfully, our application should be accessible at the address [ http://127.0.0.1:5000 ]. Here is our application with bootstrap styling as shown below.
There you have it. Thanks for reading. Happy Coding.