How to File Upload using Dropzone Js in Django Python?

Published On: 05/07/2022 | Category: Django Python


Hi Dev,

In this tutorial we will go over the demonstration of django python dropzone image upload tutorial. you can see django multiple image upload with dropzone.js. In this article, we will implement a django python drag and drop file/image upload using dropzone js. this example will help you how to file upload using dropzone js in django python.

Here i explained simply step by step it's simple example of how to file upload using dropzone js in django python.

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 dropzone
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',
    'dropzone',
]
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 company/models.py file and add the following code:

company/models.py

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)

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 company/migrations/0001_initial.py

company/migrations/0001_initial.py
# Generated by Django 2.1 on 2022-07-02 07:10

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Image',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('image', models.ImageField(upload_to='images/')),
                ('date', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'ordering': ['-date'],
            },
        ),
    ]

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 dropzone/views.py file and add:

dropzone/views.py
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':'false'})
Step 8 : Creating the Templates

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Django Dropzone Image Upload Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/6.0.0-beta.2/dropzone-min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/6.0.0-beta.2/dropzone.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <style type="text/css">
        .dz {
            border: dashed !important;
            border-radius: 10px !important;
        }
        .dz:hover {
            background-color: aliceblue !important;
        }
        .dz-success-mark{
            background-color: unset !important;
        }
        .dz-success-mark svg{
            background-color: green;
            border-radius: 50%;
            opacity: 0.7;
        }
    </style>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3>Django Python Drag and Drop File Upload with Dropzone JS - <span class="text-primary">Tuts-Station.com</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12">
                                <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>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">

Dropzone.autoDiscover=false;

/*------------------------------------------
--------------------------------------------
About 
--------------------------------------------
--------------------------------------------*/
const myDropzone= new Dropzone('#my-dropzone',{
    url: '{% url "upload" %}',
    thumbnailWidth: 200,
    maxFiles:5,
    maxFilesize:2,
    acceptedFiles:"image/jpeg,image/png,image/gif",
})

</script>
</html>
Step 9 : Creating Urls

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

dropzone/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('upload/', views.file_upload, name='upload'),
]

Next, we will require the modify the urls.py your root project folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('dropzone.urls')),
]
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....