Search code examples
htmldjangoimagesrc

html cannot display image in django


I have put my image file img.png and HTML file index.html in the same folder test I executed index.html in django, I wanted to display image from local

I tried

<img src='img.png'/>
<img src='./img.png'/>
<img src='..../test/img.png'/>   <!-- absolute path -->

the system all says cannot find the image file.


Solution

  • 1-Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

    2-In your settings file, define STATIC_URL, for example:

    STATIC_URL = '/static/'
    

    3-In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE:

    {% load static %}
    <img src="{% static 'my_app/example.jpg' %}" alt="My image">
    

    4-Store your static files in a folder called static in your app. For example: my_app/static/my_app/example.jpg.