Flask-Bootstrap packages Bootstrap into an extension that mostly consists of a blueprint named ‘bootstrap’. It can also create links to serve Bootstrap from a CDN.,The latest major version of Bootstrap as of this writing is Bootstrap 3. A branch of Flask-Bootstrap supporting version 2 is still supported, see the page on Using Bootstrap 2 for details.,Flask-Bootstrap tries to keep some track of Bootstrap releases. Versioning is usually in the form of Bootstrap version.``Flask-Bootstrap iteration``. For example, a version of 2.0.3.2 bundles Bootstrap version 2.0.3 and is the second release of Flask-Bootstrap containing that version.,Flask-Bootstrap can be installed using pip from PyPI. Using virtualenv is recommended – for no specific reason other than it being good practice. Installing is simple:
pip install flask - bootstrap
python setup.py develop
<!doctype html>
<html lang="en">
<head>
<title>My First Bootstrap Page</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1 class="text-primary">
Get started with Bootstrap
</h1>
<!-- Bootstrap Javascripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
$ pip install flask
from flask
import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Flask is great!'
if __name__ == '__main__':
app.run()
$ python--version Python 3.7 .2
< PROJECT ROOT> | |-- app/ | |-- static/ | | |-- <css, JS, images> # CSS files, Javascripts files | | | |-- templates/ | | | | | |-- index.html # Index File | | |-- login.html # Login Page | | |-- register.html # Registration Page | | | | | config.py # Provides APP Configuration | forms.py # Defines Forms (login, register) | models.py # Defines app models | views.py # Application Routes | |-- requirements.txt |-- run.py | |-- **************************************
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.88.1">
<title>Flask Authentication | Bootstrap v5.1</title>
<!-- CSS only -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/assets/css/custom.css">
</head>
<body>
<main>
<!-- PAGE Content -->
</main>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Now it's time to display our website! For this specific tutorial I'll just render the "index.html" template to show you that everything is working.,Since we added bootstrap to our website let's start using it! I'm going to add a simple sibebar to our base template that will show up on all of our pages. To do this I've merely stole some code from the bootstrap documentation and pasted in in the body tags of my HTML file.,Now that we've created our base template it is time to talk about template inheritance. Flask uses a templating engine called "Jinja" which allows us to inherit parent templates and override specific parts of them. To define what can be overwritten we need to create something in the base template called blocks.,To do this we will write an extends tag at the begging of our file and define the blocks we want to overwrite. Placing html code inside the blocks will allow us to show unique information on each child template.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
{ % block name_of_block % } { % endblock % }
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Test</h1>
{% endblock %}
In this Flask web development tutorial, we cover the inclusion of Bootstrap. What is Bootstrap? Bootstrap is the Holy Grail for non-web-designers. Some people just love writing custom CSS/HTML and making things "just so." Others dread doing the design and spend their time hunting for examples on Google, copying and pasting, so they can get back to what they love, programming. This is who Bootstrap is for.,Once you begin using it, and get familiar with Bootstrap, you'll see that you are not alone. You'll start seeing Bootstrap is used in an incredible number of websites. You'll recognize the navbars, buttons, pagebuttons...and more. ,To get Bootstrap, you just need to head over to http://getbootstrap.com/. Once there, download the source, and move the files you want. If you're not sure, just move everything. If you're not sure where to put everything, see the video. ,Once you have the required CSS and javascript files on your website, you can begin to reference them. See the video for a more in-depth analysis, and here is the sample code:
We don't really change the __init__.py file much, but here it is just in case:
from flask
import Flask, render_template
app = Flask(__name__)
@app.route('/')
def homepage():
title = "Epic Tutorials"
paragraph = ["wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!", "wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!wow I am learning so much great stuff!"]
try:
return render_template("index.html", title = title, paragraph = paragraph)
except Exception, e:
return str(e)
@app.route('/about')
def aboutpage():
title = "About this site"
paragraph = ["blah blah blah memememememmeme blah blah memememe"]
pageType = 'about'
return render_template("index.html", title = title, paragraph = paragraph, pageType = pageType)
@app.route('/about/contact')
def contactPage():
title = "About this site"
paragraph = ["blah blah blah memememememmeme blah blah memememe"]
pageType = 'about'
return render_template("index.html", title = title, paragraph = paragraph, pageType = pageType)
if __name__ == "__main__":
app.run(debug = True, host = '0.0.0.0', port = 8080, passthrough_errors = True)
Written on Mar 18, 2022
application├── __init__.py├── app.py-- > Flask app code and routes├── static-- > Static files│├── assets││├── main.scss-- > Main stylesheet, will
import Bootstrap and customize it││├── node_modules-- > Modules such as Bootstrap will be installed here││├── package - lock.json││└── package.json│├── css││└── scss - generated.css-- > Generated CSS file(from main.scss)│└── js│└── generated.js-- > Generated JS file└── templates-- > HTML template files├── base.html-- > Base template└── index.html-- > Template returned by the application
from flask import Flask, render_template # create app app = Flask(__name__) # app routes @app.route("/") def index(): return render_template("index.html")
{% extends "base.html" %}
<div class="container mt-5">
<h1>A Flask application with Bootstrap Sass</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
</div>
mkdir - p static / assets;
cd static / assets;
npm init;
npm install bootstrap;
cd - ;
// static/assets/main.scss
// Source: https://getbootstrap.com/docs/5.1/customize/sass/#importing
// Custom Bootstrap variables
$body - bg: black; // body background is black
$body - color: white; // body text is white
// Include all of Bootstrap
@import "node_modules/bootstrap/scss/bootstrap";
pip install Flask - Assets libsass;
Create a new folder named “Python Flask Bootstrap Demo” somewhere convenient on your computer.,Navigate to http://127.0.0.1:5000/ in your browser, and ta da there should be your Bootstrap 4 Demo homepage, served by Python Flask.,Python Turtle Graphics (16) ,Python Beginners (9)
- If you haven’t already done so, install Flask from a command line using
pip install flask
on Windows orpip3 install flask
on Mac/Linux. - Create a new folder named “Python Flask Bootstrap Demo” somewhere convenient on your computer.
- Create a file called
app.py
- Add the following contents:
from flask
import Flask, render_template
app = Flask(__name__)
@app.route("/")
def main():
return render_template('index.html')
if __name__ == "__main__":
app.run()
- Run
app.py
- You will see a message like this:
Serving Flask app "flask-hello"(lazy loading)
Environment: production
WARNING: This is a development server.Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Running on http: //127.0.0.1:5000/ (Press CTRL+C to quit)
#13 Mahdi said 2018-03-14T18:29:33Z , #15 pythoner said 2018-03-20T09:37:33Z , #16 Miguel Grinberg said 2018-03-20T17:54:40Z
Let's install this extension:
(venv) $ pip install flask - bootstrap
app/__init__.py: Flask-Bootstrap instance.
#... from flask_bootstrap import Bootstrap app = Flask(__name__) #... bootstrap = Bootstrap(app)
app/templates/base.html: Redesigned base template.
{% extends 'bootstrap/base.html' %}
{% block title %}
{% if title %}{{ title }} - Microblog{% else %}Welcome to Microblog{% endif %}
{% endblock %}
{% block navbar %}
<nav class="navbar navbar-default">
... navigation bar here (see complete code on GitHub) ...
</nav>
{% endblock %}
{% block content %}
<div class="container">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-info" role="alert">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{# application content needs to be provided in the app_content block #}
{% block app_content %}{% endblock %}
</div>
{% endblock %}
app/templates/register.html: User registration template.
{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block app_content %}
<h1>Register</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}
app/templates/_post.html: Redesigned post sub-template.
<table class="table table-hover">
<tr>
<td width="70px">
<a href="{{ url_for('user', username=post.author.username) }}">
<img src="{{ post.author.avatar(70) }}" />
</a>
</td>
<td>
<a href="{{ url_for('user', username=post.author.username) }}">
{{ post.author.username }}
</a>
says:
<br>
{{ post.body }}
</td>
</tr>
</table>
I am willing not to use bootstrap from pip package and from CDN.What things should I keep in mind apart from wtf.html and base.html ?
@Santosh: you will need to design your template inheritance structure yourself, pretty much like I was doing up until this chapter.
Is it possible to edit the bootstrap template, like change the background color, or shorten the username and password rectangular boxes that accepts the text, to make them shorter, or even center them in the Sign In page ?
@James: Absolutely.You are free to change the HTML, and add a CSS file with styles
if you want to change how the application looks.
Hi, Miguel,
Thank you
for your tutorial next chapter.
I have a question - how did you get a Search field at the Microblog bar ?
I don 't have it and I don'
t see the corresponding code at microblog files.