Bootstrap-Flask

2.5.0 · active · verified Sat Apr 11

Bootstrap-Flask is a collection of Jinja macros for Bootstrap 4 & 5 and Flask. It helps to render Flask-related data and objects to Bootstrap markup HTML more easily, such as Flask-WTF forms, data tables, and pagination. The library is actively maintained, with a recent release of 2.5.0, and typically sees updates to align with new Bootstrap versions and address Python compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Flask application, initialize Bootstrap-Flask for Bootstrap 5, define a simple Flask-WTF form, and render it using Bootstrap-Flask's `render_form` macro in a Jinja2 template. It also shows how to include Bootstrap's CSS and JS resources using the helper functions.

from flask import Flask, render_template
from flask_bootstrap import Bootstrap5
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'a_default_secret_key_for_dev')
bootstrap = Bootstrap5(app)

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 150)])
    remember = BooleanField('Remember me')
    submit = SubmitField('Log In')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = LoginForm()
    if form.validate_on_submit():
        # In a real application, process the form data (e.g., login user)
        return f"Login successful for {form.username.data}! Remember me: {form.remember.data}"
    return render_template('index.html', form=form)

# To run this, save it as app.py and create a 'templates' folder.
# Inside 'templates', create 'index.html' with the following content:
#
# <!doctype html>
# <html lang="en">
# <head>
#     <meta charset="utf-8">
#     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
#     <title>Login</title>
#     {{ bootstrap.load_css() }}
# </head>
# <body>
#     <div class="container">
#         <h2 class="mt-3">Login</h2>
#         {% from 'bootstrap5/form.html' import render_form %}
#         {{ render_form(form) }}
#     </div>
#     {{ bootstrap.load_js() }}
# </body>
# </html>
#
# Then install dependencies:
# pip install flask bootstrap-flask flask-wtf
# And run:
# export SECRET_KEY='your_strong_secret_key' # or set on Windows/Powershell
# flask run

view raw JSON →