2

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.

  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details which can be done with a [mre]. Please [edit] your question to add these details into it or we may not be able to help. – Dharman Dec 11 '19 at 21:33
  • Dharman, I've edited my question. – Bekhruz Niyazov Dec 13 '19 at 20:57

1 Answers1

1

[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.

Tox
  • 135
  • 1
  • 10