Using Bootstrap with Flask


Using Bootstrap with Flask

Getting Started with Flask

First, ensure you have Flask installed. If not, you can install it using pip:

pip install Flask

Step 1: Create a Basic Flask App

Let’s create a basic Flask application. Create a file called app.py:

from flask import Flask, render_template

app = Flask(__name__)
@app.route('/')
def form():
return render_template('form.html') if __name__ == '__main__':
app.run(debug=True)

Step 2: Create a HTML Template with Bootstrap

Next, you’ll need a HTML template to render the form. Create a folder called templates in the same directory as your app.py. Inside this folder, create a file named form.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup Form</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h2>Signup Form</h2>
<form>
<div class="mb-3">
<label for="inputEmail" class="form-label">Email address</label>
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-3">
<label for="inputPassword" class="form-label">Password</label>
<input type="password" class="form-control" id="inputPassword">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </body>
</html>

Explanation:

  • Bootstrap CSS: The Bootstrap CSS link is included in the <head> section of the HTML. This will style your form and other elements according to Bootstrap's design standards.
  • Form Elements: The form uses Bootstrap classes to style the input fields and button. This includes classes like form-control and btn btn-primary for standard styling.
  • Container: Bootstrap’s .container class is used to wrap the form for proper alignment and padding.

Step 3: Running the Flask App

  1. Run your Flask app by executing the command in the terminal:
python app.py
  1. Open your web browser and go to http://localhost:5000/. You should see a styled signup form.
Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.