Python flag jinja image file not found

Question with a beginner.

I am using Flask, a webframe for Python. Flask uses Jinja to render the template. I don’t know which version of Jinja Flask is using, and I don’t know how to get the Jinja version or the Flask version. I am using Python version 2.7.

The template contains an image in the css / image directory. This image is displayed when viewing the template as a file directly in the Firefox browser.

But not when performing the checkbox:

from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('Basic.html', name=name) if __name__ == '__main__': app.debug = True app.run() 

HTML file content:

  <!DOCTYPE HTML> <html> <body> <!-- variable example begin --> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello World!</h1> {% endif %} <!-- variable example end --> <img src="css/images/icons/resultset_previous.png" width="16" height="16" alt="previous" title="Previous" border="0"> </body> </html> 

A simple example of a template and variable executes as expected. But images are not displayed. Debug return: "GET / hello / css / images / icons / resultset_previous.png HTTP / 1.1" 404 -

I am running Flask in VirtualEnv as indicated in the documentation. The path to the image seems unknown. How to set the path?

+8
python flask jinja2
source share
2 answers

For Flask, you should store static files usually under the "static" folder, and then use the url_for function. Let's say your project is called "myproject" and, using your example, it should look something like this:

 myproject/ app.py templates/ static/ css/ images/ icons/ resultset_previous.png 

Then in the template you can call

 <img src= {{ url_for('static', filename = 'css/images/icons/resultset_previous.png') }} width="16" height="16" alt="previous" title="Previous" border="0"> 

Also, to answer your question about jinja versions etc., check this out

https://github.com/mitsuhiko/flask/blob/master/.travis-lowest-requirements.txt

+18
source share

See this section of the jar documentation.

The correct way to reference a static file from your template is:

 <img src="{{ url_for('static', filename = 'css/images/icons/resultset_previous.png') }}" width="16" height="16" alt="previous" title="Previous" border="0"> 
+7
source share

All Articles