Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display all images in a directory with flask [duplicate]

Tags:

python

html

flask

I am trying to display all images from a particular directory in static (static/plots). Here is my python:

hists = os.listdir('static/plots')
hists = ['plots/' + file for file in hists]
return render_template('report.html', hists = hists)

and my html:

<!DOCTYPE=html>
<html>
<head>
    <title>
        Store Report
    </title>
</head>
<body>
    {{first_event}} to {{second_event}}
    {% for hist in hists %}
    <img src="{{url_for('static', filename='{{hist}}')}}" alt="{{hist}}">
    {% endfor %}
</body>
</html>`

And when the template successfully renders, the templates are not fetched. Opening the image in a new tab yields: http://127.0.0.1:8080/static/%7B%7Bhist%7D%7D

I imagine the problem is with this line, but I can't figure out what's correct:

<img src="{{url_for('static', filename='{{hist}}')}}" alt="{{hist}}">

like image 313
ChootsMagoots Avatar asked Dec 18 '17 23:12

ChootsMagoots


People also ask

How to upload and display image using Python Flask?

When you hit the URL http://localhost:5000 in the browser to get the below page to upload the image. Once you select an image and upload then you will see the following screen: Hope you got an idea how to upload and display image using Python Flask.

How do I select multiple files in flask?

I am using here Flask as a web based framework on top of Python language. On the UI (User Interface) there is an input field which is used to select multiple files. To select multiple files after clicking on browse button you need to hold Ctrl key (Windows OS) on the keyboard and click on the images you want to select for upload.

How do I upload a page from a template in flask?

The default location in flask based applications of the template or view files is templates folder. This is upload.html page kept under templates directory. Now navigate to the project’s root directory using command line tool and execute the command python main.py, your server will be started on default port 5000.

What is the default directory to store flask templates in?

This is upload.html page kept under directory – templates, which is the standard directory for storing template or view file in flask application.


1 Answers

Try changing the line to this:

<img src="{{url_for('static', filename=hist)}}" alt="{{hist}}">

You had an extra set of {{ }} in there which was rendering as %7B and %7D.

like image 118
Matt Healy Avatar answered Sep 29 '22 01:09

Matt Healy