Reputation: 33
I need to add an image to my Flask webpage. And in my index.html file in templates directory there is this tag: <img src="image.jpg">
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/image.jpg")
def image():
return render_template("image.jpg")
- it does not work. I wanted an image in my webpage, but in my terminal it says that there is a 404 error with getting the image.
Upvotes: 2
Views: 8724
Reputation: 194
[Where does flask look for image files? More information can be found here.]
If you wish to render the image in the index.html file, replace the image tag in the index.html file with the following.
<img src="{{ url_for('static', filename='image.jpg') }}" />
You MUST put the image file in a folder named static at which all static files are located. This is vital as it is where the Flask framework finds the required resources at.
When you put
@app.route("/image.jpg")
def image():
return render_template("image.jpg")
you are creating a route called /image.jpg. When you go to this route, Flask will find a template, which is basically a file that ends with .html inside the templates folder. However, a static file like an image cannot be inside the templates folder.
Upvotes: 1