Trying to use image in Flask website only shows broken img icon

To display an image in a Flask website, you need to follow a few steps:

  1. Create a static folder: In your Flask project directory, create a folder named "static". This folder will store your static files, including images.

  2. Place the image file in the static folder: Move the image file you want to display into the "static" folder.

  3. Import the url_for function: In your Flask application code, import the url_for function from the flask module. This function is used to generate URLs for static files.

python from flask import Flask, render_template, url_for

  1. Set up your Flask app: Initialize your Flask application and configure the static folder.

python app = Flask(__name__, static_folder='static')

  1. Render the image in your HTML template: In your HTML template, use the url_for function to generate the URL for the image file. Then include it in an <img> tag.

html <img src="{{ url_for('static', filename='image.jpg') }}" alt="Image">

Replace 'image.jpg' with the actual filename of your image.

  1. Run your Flask app: Start your Flask application and navigate to the page where the image is supposed to be displayed. The image should now be visible.

By following these steps, you should be able to display an image in your Flask website without seeing a broken image icon.