How to create Photo Gallery with Django

Introduction

Here I will show you how to create photo gallery with Django. Django is a Python based framework used to build complete web applications. Photo gallery also known as image gallery, media gallery or photo album is used to manage your photos. You can view the images one by one from a list of images in a gallery. You can navigate to another photo in the gallery using next or previous arrow link. You can click on a particular photo to see the larger size of the thumbnail which is, by default, displayed in the gallery.

In this example I will use some sample images to create photo gallery using Django. For each thumbnail I have kept the larger size of the same image. The thumbnail images will be shown on the web page in a photo gallery and when you click on a thumbnail then the corresponding bigger size of image will be displayed.

Prerequisites

Knowledge of Python and Django Templates

Python: 3.6.5 – 3.9.5, Django: 2.2 – 3.2.4

Project Setup

You generally create a Django project anywhere on your system and under your Django project you have one or more applications.

Let’s say you have created Django project directory called gallery and you have also created an app called photo under gallery. You may check the documentation for creating Django project and apps under project.

I assume you have the required configurations for your photo in gallery/gallery/settings.py file under INSTALLED_APPS section as below:

INSTALLED_APPS = [
    'photo.apps.PhotoConfig',
	...
]

The photo.apps.PhotoConfig is formed as a dotted notation from gallery/photo/apps.py, where you will find the class name as PhotoConfig that has name photo.

In your settings file – gallery/gallery/settings.py, define MEDIA_ROOT and MEDIA_URL, for example:

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

MEDIA_URL = 'media/'

The media directory should be created under gallery directory.

If you want to put images and videos into separate folders then you can create images and videos directories under media directory.

You also need to store static resources, such as, JavaScript (js), Cascading Style Sheet (css), images into the static folder of the apps. So configure the static directory in gallery/gallery/settings.py file as shown below:

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'
photo gallery with django

Media Files

Here I will store the files locally and I will see how to access these media files into Django templates.

For this example, you will put the image files under gallery/media/images directory.

You will find a link to download the media files at the bottom of this tutorial.

You may also like to read working with media files in Django templates.

Static Resources

I will store static resources, such as, JavaScript (js), Cascading Style Sheet (css), images into the static folder of the apps.

You need to create a directory static under gallery/photo then again create a directory photo under gallery/photo/static/photo.

You will find a link to download the static resources at the bottom of this tutorial.

You may also like to read working with static resources in Django templates.

Django Templates

Here I will use template files for rendering the view. First, go through the tutorial on working with parent and child templates in Django for information on Django templates.

Create a directory called templates under gallery/photo. Then create another directory photo under templates directory.

Now I will create parent and child templates. So child template will inherit from the parent template and fill the gaps into parent template.

Create a template file base.html with the following source code and put into gallery/photo/templates/photo directory.

<!DOCTYPE html>
{% load static %}
<html>
    <head>
        <title>Django - Photo Gallery</title>
        <!-- CSS -->
        <link rel="stylesheet" href="{% static 'photo/css/style.css' %}">
        <link rel="stylesheet" href="{% static 'photo/css/simplelightbox.min.css' %}">

        <!-- JAVASCRIPT -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script type="text/javascript" src="{% static 'photo/js/simple-lightbox.min.js' %}"></script>
    </head>
    <body>
	    <div class='container'>
		    <div class="gallery">
                {% block body %}{% endblock body %}
		    </div>
		</div>
        {% block extra_js %}{% endblock extra_js %}
    </body>
</html>

The block areas in the above base or parent template file may be filled by child template.

Next create the child template file index.html with below source code and put under the same directory as parent template.

{% extends 'photo/base.html' %}

{% load photo_tags %}

{% block body %}
	{% if images %}
		{% for image in images %}
			{% with image|split:'.' as strs %}
				{% with strs|length as str_arr_len %}
					{% with str_arr_len|add:'-1' as ext_idx %}
						{% if strs|get_by_index:ext_idx == 'jpg' %}
							<a href="{{ MEDIA_URL }}images/{{ image }}">
								<img src="{{ MEDIA_URL }}images/thumbs/{{ image }}" alt="{{ image }}">
							</a>
						{% endif %}
					{% endwith %}
				{% endwith %}
			{% endwith %}
			{% if forloop.counter|divisibleby:4 %}
				<div class="clear"></div>
			{% endif %}
		{% endfor %}
	{% else %}
		<p>No image available.</p>
	{% endif %}
{% endblock body %}

{% block extra_js %}
	<script type='text/javascript'>
		$(document).ready(function() {
			$('.gallery a').simpleLightbox();
		});
	</script>
{% endblock extra_js %}

To create photo or image gallery in Django I have used jQuery library Lightbox to display the images into gallery.

In the above child template I am iterating with images, then I check each image’s extension to check whether it ends with “jpg” or not. You can also check for other extensions of the images to make sure the file is image file.

Then I build the anchor tag (hyper link) with image and thumbnail.

Custom Template Tags

Notice that I have loaded custom template tag using {% load photo_tag %}. This custom template tag is required to split the string in template file and to retrieve the array element by index variable.

If you need more details on how to create custom template tags and filters in Django then please read custom tags.

Create a folder called templatetags under gallery/photo directory. Now create the file photo_tags.py under templatetags folder and define below filters in it.

from django import template

register = template.Library()

@register.filter(name='split')
def split(str, key):
    return str.split(key)

@register.filter
def get_by_index(a, i):
    return a[i]

Request URI

You need to define URIs into gallery/photo/views.py file. I will define here index request, so the URL will be http://localhost:8000/photo, where 8000 is the default port of the development server, photo (index URI) is our app under the project – gallery.

import os
from django.conf import settings
from django.shortcuts import render
from django.templatetags.static import static

# Create your views here.
def index(request):
    path = settings.MEDIA_ROOT
    img_list = os.listdir(path + '/images')
    context = {'images' : img_list}
    return render(request, "photo/index.html", context)

So in the above code I have listed all images from the media path and store into images variable, which is passed to the template view file – index.html that inherits from base.html template.

Define URL and Serving Media Files

You have told Django where the media folder should be, and the correct URLs to access them, you need to serve all requests to the folders correctly.

Usually when you are in production, you want the webserver to take care of serving your static files and media files.

If you are developing though, you can just get the django development server to serve them for you.

You define index path and media URLs to your gallery/photo/urls.py as shown below:

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from . import views

urlpatterns = [
    path('photo/', views.index, name='index'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Running the Application

Navigate to the directory gallery from command prompt and execute the command manage.py runserver, you will see below output in the command prompt. You will also see the version of Django in the output:

photot gallery in django

In the above file you see an warning, so you can run the command manage.py migrate to migrate your scripts.

Testing the Application

When you hit the URL http:localhost:8000/photo/, you will see the below screen on the browser. When you mouse over on of the photo then you will see the image slightly pops up:

photo gallery with django

When you click on the image then you can see similar to below screen.

You can navigate to right or left to see all the images one by one. You can also close the gallery by clicking on the x button on top right corner of the page.

You can also see which photo your are currently viewing and what is the total number of images in the gallery.

photo gallery with django

Source Code

Download

1 thought on “How to create Photo Gallery with Django

  1. The source code doesn’t have a next and previous icon and function as illustrated in the pop-up image

    Or I am missing something ?

Leave a Reply

Your email address will not be published. Required fields are marked *