Back to Python
2026-03-315 min read

Bootstrap Examples (Python Programming)

Learn Bootstrap Examples (Python Programming) step by step with clear examples and exercises.

Title: Bootstrap Examples (Python Programming)

Why This Matters

Bootstrap is a powerful front-end framework used for creating responsive, mobile-first websites. Integrating it with Python programming, through the Flask extension Flask-Bootstrap, can significantly streamline web development projects and produce visually appealing results. This lesson will walk you through examples of using Bootstrap with Python, helping you understand its practical applications and common pitfalls.

Prerequisites

Before diving into Bootstrap examples, ensure you have a basic understanding of:

  1. Python programming fundamentals (variables, functions, loops, etc.)
  2. Web development basics (HTML, CSS)
  3. Flask web framework in Python
  4. Familiarity with SQLAlchemy for database interaction (if following the todo list example)
  5. Installing and managing Python packages using pip

Core Concept

To use Bootstrap with Flask, we first need to install the Flask-Bootstrap extension:

pip install flask-bootstrap

Now that we have the necessary package installed, let's create a new Flask application and import the required modules:

from flask import Flask, render_template, request, redirect, url_for
from flask_bootstrap import Bootstrap
from sqlalchemy import create_engine, Table, MetaData

app = Flask(__name__)
Bootstrap(app)

Assuming you have a SQLite database setup with the following tables:

users (id, name, email)

todos (id, content, completed)

db = create_engine('sqlite:///mydatabase.db')

metadata = MetaData()

users = Table('users', metadata, autoload_with=db)

todos = Table('todos', metadata, autoload_with=db)


In the above code, we've created a new Flask application and initialized `Flask-Bootstrap`. We've also set up SQLAlchemy to connect to our database. Next, let's create a simple HTML template that includes Bootstrap styles:

My Flask App

{% with messages = get_flashed_messages() %}

{% if messages %}

{% for message in messages %}

{{ message }}

{% endfor %}

{% endif %}

{% block content %}{% endblock %}


In the above HTML template, we've included Bootstrap CSS and JavaScript files from a CDN. The `{% block content %}{% endblock %}` section is where our Flask application will render dynamic content.

Now that we have our base HTML template set up, let's create a simple route to display some text:

@app.route('/')

def home():

Assuming you have data in the database:

users_data = db.execute(users.select()).fetchall()

todos_data = db.execute(todos.select()).fetchall()

return render_template('index.html', title='Home', users=users_data, todos=todos_data)


In the above code, we've created a new route called `/`, which returns our HTML template and passes in some variables (title, users_data, todos_data). When you run this application, you should see the Bootstrap-styled data from your database displayed on your browser.

Worked Example

Let's create a more complex example by building a simple todo list application using Bootstrap and Flask. First, we'll create an HTML template for our todos:

<ul id="todos">
{% for todo in todos %}
<li class="{% if todo.completed %}text-decoration-line-through{% endif %}">{{ todo.content }}</li>
{% endfor %}
</ul>
<form action="/add_todo" method="post">
<input type="text" name="todo" placeholder="Add a new todo">
<button type="submit">Add</button>
</form>

Next, we'll create routes to handle adding todos and marking them as completed:

@app.route('/add_todo', methods=['POST'])
def add_todo():
todo = request.form['todo']
db.execute(todos.insert().values(content=todo, completed=False))
db.commit()
flash('Todo added successfully!')
return redirect(url_for('home'))

@app.route('/toggle_complete/<int:todo_id>')
def toggle_complete(todo_id):
todo = db.execute(todos.select().where(todos.c.id == todo_id)).scalar()
if todo:
db.execute(todos.update().where(todos.c.id == todo_id).values(completed=not todo.completed))
db.commit()
flash('Todo status updated successfully!')
return redirect(url_for('home'))

In the above code, we've created a new route called /add_todo, which receives the user's input from the form and inserts it into our database. We also have a route called /toggle_complete/ that allows users to mark todos as completed by clicking on them.

Common Mistakes

  1. Forgetting to import necessary modules: Ensure you import both Flask and Bootstrap at the beginning of your Python script, along with any other required modules like SQLAlchemy if needed.
  2. Not including Bootstrap CSS and JavaScript in your HTML template: Make sure you link the appropriate files from a CDN within the `` section of your HTML template.
  3. Misconfiguring your Flask application: Ensure that you've initialized Bootstrap(app), created routes for adding todos, marking them as completed, and any other necessary functionality.
  4. Not committing changes to the database: Don't forget to call db.commit() after inserting data into your database or updating records in the examples provided.
  5. Incorrectly formatting Bootstrap CSS classes: Ensure you use the correct syntax for applying Bootstrap classes, such as text-decoration-line-through for strikethrough text.

Practice Questions

  1. Create a new Flask application that displays a simple Bootstrap-styled form for users to input their name and email address, then saves this information to a SQLite database using SQLAlchemy.
  2. Modify the todo list example to allow users to mark todos as completed by clicking on them and display completed todos in a separate section of your HTML template.
  3. Create a new Flask application that displays a Bootstrap-styled table with data fetched from an API (e.g., JSONPlaceholder).
  4. Extend the todo list example to allow users to edit and delete their todos using Bootstrap modal forms.
  5. Implement user authentication in your todo list application, requiring users to log in before they can add, edit, or delete todos.

FAQ

Q: Why should I use Bootstrap with Flask?

A: Using Bootstrap with Flask can help you create responsive, mobile-first websites more efficiently by providing pre-built CSS classes for common UI components and integrating seamlessly with the Flask framework.

Q: How do I include Bootstrap in my Flask application?

A: Install the Flask-Bootstrap extension using pip and import it into your Python script. Include Bootstrap CSS and JavaScript files from a CDN within the `` section of your HTML template.

Q: How do I create dynamic content with Bootstrap in my Flask application?

A: Use Flask's render_template() function to render an HTML template with dynamic content, passing variables as needed. Include a {% block content %}{% endblock %} section within your HTML template where Flask will insert the dynamic content.

Q: How do I handle user input in my Bootstrap-powered Flask application?

A: Use Flask's built-in request object to access user input from forms, then use SQLAlchemy or another database toolkit to interact with your database.

Q: Can I customize the Bootstrap CSS classes used in my Flask application?

A: Yes, you can override the default Bootstrap CSS by adding your own styles within your HTML template or through a separate CSS file linked from your HTML template.

Bootstrap Examples (Python Programming) | Python | XQA Learn