Django – How to Display Images in Template from Static Directory

In this post, we’ll learn how we can display static images in the Django Template.

Setup Project

Follow the below steps to create a new Django Project

django-admin startproject mysite

For creating an app

django-admin startapp my_app

Now register the my_app in setting.py.

INSTALLED_APPS = [
    '...',
    'my_app.apps.MyAppConfig',
]

Configuring static directory in settings.py file

To display any static file such as images, CSS, or javascript, etc we have to specify that in settings.py file.
Add the below code at the end of settings.py file.

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, ""),
    os.path.join(BASE_DIR, "static"),
    os.path.join(BASE_DIR, "mysite/static"),
]

MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_URL)

Now in our project root directory create a folder static and add some images files so that we can display them in the template.

Creating Template for Displaying Image

In my_app/urls.py file create a path for the template.

from django.urls import path
from my_app import views

app_name = "my_app"

urlpatterns = [
    path("gallery", views.gallery, name="gallery")
]

In my_app/views.py file create a function to render a template.

from django.shortcuts import render

# Create your views here.
def gallery(request):
    template_path = "my_app/gallery.html"
    
    context = {
        "images" : [
            "bg-1.png",
            "bg-2.jpg",
        ]
    }

    return render(request, template_path,context)

Now create template gallery.html in path my_app/templates/my_app/gallery.html.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Gallery</title>
    <style>
        div > .img-div{
            width: 200px;
            padding: 15px;
            box-sizing: border-box;
            float: left;
        }
    </style>
</head>
<body>
    <h3>Welcome To My Gallery</h3>
    <div>
        {% for img in images %}
        <div class="img-div" >
            <img src="{% static 'media/' %}{{img}}" style="width: 100%;" />
        </div>
        {% endfor %}    
    </div>
</body>
</html>
The {% load static %} is important and must be mentioned at the top of the page. And you can also visit official documentation on Django Static Files.
Django Framework - Displaying Images from Static Directory in Template
Django Framework – Displaying Images from Static Directory in Template

 

Related Posts

Summary
Review Date
Reviewed Item
Django - How to Display Images in Template from Static Directory
Author Rating
51star1star1star1star1star
Software Name
Django Framework
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development