How to Multiple File Upload Using Ajax in Django?

Published On: 08/09/2022 | Category: Django

Hi Dev,

If you need to see example of how to multiple file upload using ajax in django. Here you will learn django ajax multiple file upload example. I would like to share with you django jquery ajax multiple file upload example tutorial. if you have question about how to multiple upload files using django jquery and ajax then I will give simple example with solution. Here, Creating a basic example of how to upload multiple file using ajax in django.

Here, in this example, we will create "Document" table with a file column. Then we will create a form with file input, when you submit it will send the file via jquery ajax request and store the image into the folder and database.

You can use these examples with django3 (django 3) version.

Here i explained simply step by step example of how to file upload using ajax in django.

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

Now we'll create a single app called core to store a list of files name. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 startapp core
Step 3: Update

In this step we require to do two things in our is register our new app in INSTALLED_APPS within our second is to configure our media folder. Add the below lines to your file:

Next, you need to add it in the file as follows:
import os


MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Step 4: Create a Model

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

from django.db import models

class Document(models.Model):
    file = models.FileField(upload_to="documents/%Y/%m/%d")

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

python makemigrations
python migrate
Step 5: Create a Form

In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.

from django import forms
from .models import *
from django.utils.translation import gettext as _

class DocumentForm(forms.ModelForm):

    file = forms.FileField(
                    label=_('Choose File'),
                    error_messages = {'required':'The file field is required.','invalid':_("Files only")}, 
                    widget=forms.FileInput(attrs={'multiple':True,'class': 'form-control custom-file-input','id' : 'customFile'}

    class Meta:
        model = Document
        fields = ['file',]
Step 6: Creating the Views

In this step, we need to configure our views. The file_upload page will just be a template and store to multiple image database and our media folder.So, open the core/ file and add:

from django.shortcuts import render
from .forms import *
from .models import *
from django.contrib import messages
from django.http import JsonResponse

# Create your views here.
def file_upload(request):

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        files = request.FILES.getlist('file')

        if form.is_valid():
            for file in files:
                ext = os.path.splitext([1]
                valid_extensions = ['.pdf', '.csv', '.doc', '.docx', '.xlsx', '.xlx']
                if ext.lower() in valid_extensions:

            if ext.lower() in valid_extensions:
                return JsonResponse({'success': True, 'message': 'File Uploaded Successfully!'})
                return JsonResponse({'error': True, 'msg': 'Unsupported file extension!'})
            return JsonResponse({'error': True, 'errors': form.errors})
        form = DocumentForm()

    return render(request, 'index.html', {'form' : form})
Step 7: Creating the Template

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

<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <script src=""></script>
    <style type="text/css">
            background-color: #f7fcff;
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5>How to Multiple File Upload using Ajax in Django? - <span class="text-primary"></span></h5>
                    <div class="card-body">
                        <div class="row success-msg-main" style="display: none;">
                            <div class="col-lg-12">
                                <div class="alert alert-success success-msg"></div>
                        <form enctype="multipart/form-data" method="post" id="id_ajax_upload_form" novalidate>
                            {% csrf_token %}
                             <div class="custom-file">
                                {% for field in form %}
                                    <label class="custom-file-label" for="customFile">{{ field.label }}</label>
                                    {{ field }}
                                {% endfor %}
                             <small class="mt-2">(File extension must be pdf, csv, doc, docx, xlsx, xlx format.)</small>
                             <div class="row mt-4">
                                <div class="col-lg-12 text-center">
                                    <button class="btn btn-primary">Submit</button>
<script type="text/javascript">

    Custom File Input 
    $(".custom-file-input").on("change", function() {
      var fileName = $(this).val().split("\\").pop();

    Ajax Image Upload 
        $form = $(this)
        var formData = new FormData(this);
            url: '{% url "file_upload" %}',
            type: 'POST',
            data: formData,
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    $('.success-msg-main').css('display', 'block');
                }else if(response.errors) {
                    $.each(response.errors, function(name, error){
                        error = '<small class="text-danger error mt-2">' + error + '</small>'
                        $form.find('[name=' + name + ']').after(error);
                    error = '<small class="text-danger error mt-2">' + response.msg + '</small>'
                    $form.find('[name=' + 'file' + ']').after(error);
            cache: false,
            contentType: false,
            processData: false
Step 8: Creating Urls

In this section, we need a file within the core app however Django doesn't create one for us with the startapp command. Create core/ with your text editor and paste below code:

from django.urls import path
from . import views

urlpatterns = [
    path('file/', views.file_upload, name="file_upload"),

Next, we require to add a URL path for our example project which can be done by importing include and setting a path for it.

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

urlpatterns = [
    path("", include('core.urls')),

if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,

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 runserver

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

I Hope It will help you....

Happy Coding!