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:
Create a static folder: In your Flask project directory, create a folder named "static". This folder will store your static files, including images.
Place the image file in the static folder: Move the image file you want to display into the "static" folder.
Import the
url_for
function: In your Flask application code, import theurl_for
function from theflask
module. This function is used to generate URLs for static files.
python
from flask import Flask, render_template, url_for
- Set up your Flask app: Initialize your Flask application and configure the static folder.
python
app = Flask(__name__, static_folder='static')
- 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.
- 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.