Introduction

Here we will see how to create photo gallery with Django. 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.

In this example we will use some images to create photo gallery using Django. We will have corresponding thumbnails for the images. 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 version – 3.6.5, Django version – 2.2

Python and Django setup

Example with Source Code

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

Project Configuration

Let’s say you have created Django project 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 in 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.

We 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)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

Putting media files

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

For this example we 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.

Putting static resources

We 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.

Creating templates

Here we 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 we 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 we have used jQuery library Lightbox to display the images into gallery.

In the above child template we are iterating with images, then we 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 we build the anchor tag (hyper link) with image and thumbnail.

Creating custom template tags

Notice that we 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 here.

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]

Defining request URI

We define URIs into gallery/photo/views.py file. We will define here our index request so our 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 we list 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.

We define our index path and media URLs to our 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('', 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 python manage.py runserver, you will see below output in the command prompt:

photot gallery in django

Testing the application

When you hit the URL http:localhost:8000/photo/, you will see the below screen on the browser:

photo gallery with django

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

Please click here to download the source code.

If you have better idea to write code for the above photo gallery then let me know.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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