skip to Main Content

I have a "templates" folder and a "images" folder located in my project directory. Inside the templates folder I have the base.html file that is supposed to display the image located in the images folder. However, when i go on the website and open the console, it says: GET http://127.0.0.1:5000/images/address.png 404 (NOT FOUND). The image is not displayed.

base.html code

main.py

from flask import Flask, render_template, request, redirect, session, url_for
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# Routes
@app.route('/')
def index():

    return redirect(url_for('home'))

@app.route('/home')
def home():

    return render_template('base.html')

@app.route('/rd')
def rd():

    return 

@app.route('/about', methods=['GET'])
def about():

    return render_template('about.html')

if __name__ == '__main__':

    app.run(debug=True)

I have tried changing the directory to /images/address.png, ./images/address.png and etc., non worked

I expected the image to show up

2

Answers


  1. Updated answer

    Put the ‘images’ folder into ‘static’ folder.
    Replace ‘about.html’ line 6 with <img class="tinyimg" src="static/images/address.png">.

    Flask serves static files via the static folder by default.

    Old answer

    Please post your source code in text.
    You’ll want to use ../images/address.png.

    Explanation
    ../ moves up one directory level from the current location. Since your HTML is running in "PermanentEstet/templates", you’ll need to move up from "templates" folder, and into "PermanentEstet/images".

    Login or Signup to reply.
  2. You need to store your images in the /static folder, and use the url_for function to retrieve them in the html code.

    You can also use app.static_folder=/path to change the static folder path.

    Example

    source

    File structure

    static
      |- images
          |- daniel-shapiro--QtglPvx3I0-unsplash.jpg
    
    templates
      |- index.html
    
    main.py
    

    main.py

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return render_template('index.html')
    
    if __name__ == '__main__':
        app.run()
    

    index.html

    <h3>This is an apple</h3>
    
    <img
      src="{{ url_for('static', filename='images/daniel-shapiro--QtglPvx3I0-unsplash.jpg') }}"
      class="image"
    />
    
    <style>
      .image {
        width: 200px;
      }
    </style>
    

    codesandbox

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search