Create Image Gallery with Multiple Image Upload in Django

An image gallery is a fantastic way to showcase visual content, and in this tutorial, we’ll explore how to build one in a Django web application. To take it a step further, we’ll enable users to upload multiple images directly within the gallery page itself. By following this comprehensive guide, you’ll learn how to create a seamless user experience that allows for both image uploading and gallery display on the same page.

Prerequisites

Before we dive into the tutorial, make sure you have the following prerequisites:

  • Django: Ensure Django is installed. If not, you can install it using pip:
  pip install Django
  • Basic Knowledge of Django: Familiarity with Django concepts like views, templates, models, and forms will be helpful.

Note: This project can be used with any database as it is. No changes needed. You can learn how to Configure Database with our bellow blogs:

Step 1: Setting Up Your Django Project

Start by creating a new Django project and app. Open your terminal and run the following commands:

django-admin startproject myproject
cd myproject
python manage.py startapp imagegallery

Step 2: Defining Models

To manage images, create a model that represents the images in your gallery. Open imagegallery/models.py and define the model:

from django.db import models

class GalleryImage(models.Model):
    image = models.ImageField(upload_to='gallery/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.image)

Step 3: Creating Forms

Let’s create a form that allows users to upload multiple images. In imagegallery/forms.py, define the UploadImageForm form using the MultipleFileField:

from django import forms
from .models import GalleryImage

class MultipleFileInput(forms.ClearableFileInput):
    allow_multiple_selected = True

class MultipleFileField(forms.FileField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault("widget", MultipleFileInput())
        super().__init__(*args, **kwargs)

    def clean(self, data, initial=None):
        single_file_clean = super().clean
        if isinstance(data, (list, tuple)):
            result = [single_file_clean(d, initial) for d in data]
        else:
            result = single_file_clean(data, initial)
        return result

class UploadImageForm(forms.ModelForm):
    images = MultipleFileField(widget=MultipleFileInput())

    class Meta:
        model = GalleryImage
        fields = ('images',)

Step 4: Creating Views and Templates

Create a view that handles both the gallery display and the image uploading on the same page. Open imagegallery/views.py and define the view:

from django.shortcuts import render, redirect
from .models import GalleryImage
from .forms import UploadImageForm

def gallery_with_upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            for image in request.FILES.getlist('images'):
                GalleryImage.objects.create(image=image)
    else:
        form = UploadImageForm()

    gallery = GalleryImage.objects.all()
    return render(request, 'gallery_with_upload.html', {'form': form, 'gallery': gallery})

Create a template named gallery_with_upload.html inside imagegallery/templates:

<!DOCTYPE html>
<html>
<head>
    <title>Image Gallery with Upload</title>
    <style>
        .gallery {
            display: flex;
            flex-wrap: wrap;
        }
        .gallery-item {
            width: 200px;
            margin: 10px;
        }
        .gallery-item img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <h2>Image Gallery with Upload</h2>

    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

    <h3>Gallery Images:</h3>
    <div class="gallery">
        {% for image in gallery %}
            <div class="gallery-item">
                <img src="{{ image.image.url }}" alt="Gallery Image">
            </div>
        {% empty %}
            <p>No images in the gallery yet.</p>
        {% endfor %}
    </div>
</body>
</html>

Step 5: Configuring URLs

Configure URLs to map to the view you’ve created. Open imagegallery/urls.py and define the URL:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.gallery_with_upload, name='gallery_with_upload'),
]

Step 7: Configuring Media Settings and App URL

In your project’s settings (myproject/settings.py), configure the media settings to manage image uploads. Add the following lines at the end of the file:

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

Lastly, include the URLs of the imagegallery app in the project’s main urls.py file (myproject/urls.py):

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('imageoperations.urls')),
]

from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 8: Running Migrations and Starting the Server

Run the initial migrations to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate

Run the development server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser to experience the image gallery with the capability to upload multiple images on the same page.

Conclusion

You’ve successfully created an image gallery with the ability to upload multiple images in the same page using Django. This guide has covered the setup of models, forms, views, templates, and URLs, allowing you to seamlessly integrate image uploading into your gallery display. By following these steps, you’ve empowered your Django application to provide users with a dynamic and engaging visual experience.

Find this project on Github.

Blogs You Might Like to Read!