37

I am trying to pass a filename of an image and render it on a template, Although I am passing the actual name through it does not display on the page

@app.route('/', methods=['GET','POST'])
@app.route('/start', methods=['GET','POST'])
def start():
person_to_show = 'tim'
profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg")
return render_template('start.html',profilepic_filename  =profilepic_filename )

For example: profilepic_filename = /data/tim/img.jpg I have tried

{{profilepic_filename}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>

And I have also tried

<img src="{{profilepic_filename}}"></img>

Neither of which worked

VC.One
  • 14,790
  • 4
  • 25
  • 57
Darren rogers
  • 627
  • 2
  • 8
  • 17

1 Answers1

80

I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template.

In application.py:

from flask import Flask, render_template
import os

PEOPLE_FOLDER = os.path.join('static', 'people_photo')

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER

@app.route('/')
@app.route('/index')
def show_index():
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg')
    return render_template("index.html", user_image = full_filename)

In index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <img src="{{ user_image }}" alt="User Image">
</body>
</html>

Output:

enter image description here

ngoldbaum
  • 5,430
  • 3
  • 28
  • 35
arshovon
  • 13,270
  • 9
  • 51
  • 69
  • 3
    Did anyone else have trouble getting this to work? pycharm tells me `Process finished with exit code 0` but `localhost:5000` isn't showing any images – Nathan majicvr.com Apr 20 '18 at 20:59
  • 1
    @frank, `localhost:5000`is available as long as the program remains in running state. There might be something that stopped the program and you got `Process finished with exit code 0`. – arshovon Apr 21 '18 at 03:53
  • 2
    How can we display an image from S3 links? Any help would be appreciated. – vinit kantrod Feb 06 '19 at 20:54
  • 1
    @vinitkantrod, it is not in the scope of this question. It will be better if you can create a new question regarding S3 bucket image usage in Flask. I think future readers will be benefited. – arshovon Feb 07 '19 at 03:43
  • 3
    is there a way to use a sub-folder instead of the static folder and pass through the `local ressource` error? – Bando Aug 13 '19 at 09:15
  • 1
    add app.run(host='0.0.0.0') to end of the file to start this as a server – HarshaXsoad Feb 07 '20 at 15:26
  • Somehow the method in this answer by @arshovon did not work for me but I followed the method in this other blog which worked for me: https://kanchanardj.medium.com/how-to-add-images-to-html-in-a-flask-app-4dbcc92e3aeb – abggcv May 11 '23 at 05:01