How to Multiple image Upload in Python Django ?

Published On: 29/06/2022 | Category: Django Python


Hi Dev,

In this tutorial, I will show you how to multiple image upload in python django. This post will give you simple example of how to multiple image upload in python django app. We will look at example of how to multiple image upload in python django bootstrap. if you want to see example of how to multiple image upload in python django example then you are a right place.

Here i explained simply step by step example of how to multiple image upload in python django in database.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp multipleImage
Step 3 : Update setting.py

In this step we require to do two things in our settings.py file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

import os

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'multipleImage',
]

....
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
....
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create a Model

In this step we will require the database model for storing contacts.Open the multipleImage/models.py file and add the following code:

multipleImage/models.py
from django.db import models
class MultipleImage(models.Model):
    images = models.FileField()

After creating these model, you need to create migrations using the following command:

Step 6 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the multipleImage/migrations/0001_initial.py

multipleImage/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-06-29 04:55

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='MultipleImage',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('images', models.FileField(upload_to='')),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 7 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the multipleImage/views.py file and add:

multipleImage/views.py
from django.shortcuts import render
from .models import MultipleImage
from django.contrib import messages

# Create your views here.

def multipleUpload(request):
    imagesUpload = ''
    
    if request.method == "POST":
        images = request.FILES.getlist('images')
        for image in images:
            imagesUpload = MultipleImage.objects.create(images=image)
    images = MultipleImage.objects.all()

    if imagesUpload:
        messages.success(request, 'Image Upload Successfully')   
        
    return render(request, 'index.html', {'images': images})
Step 8 : Creating the Views

Next, open the multipleImage/templates/index.html file and the add:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>How to Multiple image Upload in Python Django ?</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-9">
                {% if messages %}
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                        {% for message in messages %}
                            {{ message }}
                        {% endfor %}
                    </div>
                {% endif %}
                <div class="card">
                    <div class="card-header">
                        <h4>How to Multiple image Upload in Python Django ? - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <form method = "post" enctype="multipart/form-data">
                            {% csrf_token %}
                            <input type="file" class="form-control" name="images" multiple>
                            <hr>
                            <div class="row mt-2">
                                <div class="col-md-12 text-center">
                                    <button type="submit" class="btn btn-success">Upload</button>
                                </div>
                            </div>
                        </form>

                        <hr>
                        {% for img in images %}
                        <img src="{{img.images.url}}" alt="Image" width="100" height="100" style="border: 1px solid black;">
                        {% endfor %}
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 9 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py multipleImage/urls.py file and update it as follows:

multipleImage/urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from multipleImage.views import *
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('image-upload', multipleUpload, name = 'multipleUpload'),
]

if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

I Hope It will help you....