DEV Community

Cover image for Upload multiple images to your Django app using Dropzone Js
Nick Langat
Nick Langat

Posted on • Edited on

Upload multiple images to your Django app using Dropzone Js

Hello guys it's been a minute! I was on a small break but now am back and in this tutorial we are going to learn how we can upload multiple images to a Django back end. By default the Django behavior is that you select a single image and upload it to the server then repeat which begs the question isn't that a time consuming and tedious process, say if we have 1000 images? It is.
Fortunately, there is a tool that can help us go around this problem, a JavaScript library called Dropzone . Let's not waste more seconds, let's get into it!

PROJECT SETUP

Let's quickly navigate to our desktop directory and bootstrap the back end.

cd ~/Desktop

mkdir django_dropzone && cd django_dropzone

virtualenv env

source env/bin/activate

pip install django

django-admin startproject mysite .

python manage.py startapp core 
Enter fullscreen mode Exit fullscreen mode

Next add core to the list of installed apps in settings.py.
While there also update the templates section as follows:

import os

'DIRS': [os.path.join(BASE_DIR, 'templates')],
Enter fullscreen mode Exit fullscreen mode

Then also update the static settings like so:

STATIC_URL = '/static/'
if DEBUG:
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Enter fullscreen mode Exit fullscreen mode

IMAGE MODEL

We have set up our settings.py and it's good to go. Move to core/models.py and add the following code:

from django.db import models

# Create your models here.

class Image(models.Model):
    image=models.ImageField(upload_to='images/')
    date = models.DateTimeField( auto_now_add=True)

    class Meta:
        ordering=['-date']

    def __str__(self):
        return str(self.date)
Enter fullscreen mode Exit fullscreen mode

Go ahead and makemigrations then migrate to apply the changes to the db.
Next we go the the views.py. Write the following code to it.

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Image
# Create your views here.

def home(request):
    images=Image.objects.all()
    context={
        'images':images
    }
    return render(request, 'index.html', context)

def file_upload(request):
    if request.method == 'POST':
        my_file=request.FILES.get('file')
        Image.objects.create(image=my_file)
        return HttpResponse('')
    return JsonResponse({'post':'fasle'})
Enter fullscreen mode Exit fullscreen mode

Next create core/urls.py and add the following code to it:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name='home'),
    path('upload/', views.file_upload),
]
Enter fullscreen mode Exit fullscreen mode

To finalise the Python part, add the following code to the project's urls.py

rom django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

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

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

DROPZONE SETUP

We are done with the logic let's do the UI stuff. Create a folder called static and in it create two files:

touch static/main.js

touch static/style.css

Enter fullscreen mode Exit fullscreen mode

Add the following code to main.js:

Dropzone.autoDiscover=false;
const myDropzone= new Dropzone('#my-dropzone',{
    url:'upload/',
    maxFiles:5,
    maxFilesize:2,
    acceptedFiles:'.jpg',
})
Enter fullscreen mode Exit fullscreen mode

And the following to style.css:

body {
    background-color: #f8f8f8 !important;
}

.dz {
    border: dashed !important;
    background-color: #ccc !important;
    border-radius: 10px !important;
}

.dz:hover {
    background-color: aliceblue !important;
}
Enter fullscreen mode Exit fullscreen mode

Next create a folder called templates and in it create two files:

touch templates/base.html

touch templates/index.html

Enter fullscreen mode Exit fullscreen mode

Add the following code to base.html

{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- Font awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- custom css & js -->
    <link rel="stylesheet" href="{% static 'style.css' %}">
    <script src="{% static 'main.js' %}" defer></script>

    <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
    <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">


    <title>Drag and Drop Django| {% block title %}{% endblock title %}</title>
  </head>
  <body>
    <div class="container mt-3">
        {% block content %}
        {% endblock content %}
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And the following to index.html:

{% extends 'base.html' %}

{%block content%}
<h6>UPLOAD MULTIPLE IMAGES NOW</h6>
<br>
<form enctype='multipart/form-data' action="upload/" method='POST' class="dropzone dz" id="my-dropzone" >
    {% csrf_token %}
    <div class="fallback">
      <input name="file" type="file" multiple />
    </div>
</form>
{%endblock%}
Enter fullscreen mode Exit fullscreen mode

SPIN UP THE SERVER

Now go to the terminal and:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Check the browser and upload images, be sure to select multiple.

1
and
2

MISSION SUCCESS

Yeah that should do it for this article. Thanks for keeping me company and coding along. You can grab the source code of this project here
You can connect with me on LinkedIn and on Twitter
Cheers and see you next time!

Top comments (3)

Collapse
 
ionecum profile image
ionecum • Edited

Hello, good tutorial but an error, some inaccuracies and even additional questions should be raised:

  1. In views.py return JsonResponse({'post':'false'})

It's 'false', not 'fasle'.

  1. The js scripts in base.html should always be put at the end. It is a SEO good practice and in general.

  2. Why do you import JQuery if you don't use it?

  3. Is it really necessary to import so many scripts?

  4. What about accepting more filetypes? jpg is not the only one. And if I want to accept more?

  5. What is the Dropzone object and what does it do? You should explain things, not only put the way to do them.

  6. Why does main.js is imported before dropzone.js? And what is defer?

  7. How about remove an uploaded picture? In drag and dropping multiple files he may have a mistake.

I think the most important point is 8. In real world applications, adding an "x" to remove wrongly uploaded images is really important. And, if your tutorial is really for beginners, you should definitively teach the way to do it.

Collapse
 
lewiskori profile image
Lewis kori

I use this all the time 😁. Thanks

Collapse
 
nick_langat profile image
Nick Langat

Life saver!