Django Ajax Image Upload Example

Published On: 01/08/2022 | Category: Django Python

Hi Dev,

Now, let's see post of django ajax image upload example. This post will give you simple example of ajax file upload django. you will learn how to send image data using ajax. I would like to share with you django ajax image upload example form. You just need to some step to done how to image upload using ajax in django.

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

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

let's see below simple example with output:

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 startapp core
Step 3 : Update

Here, do not forget to register the new app in the file. Under installed apps, just add ‘core’ to the list:


Step 4 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 5: 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
from django.contrib.auth.models import User

# Create your models here.
class Image(models.Model):
    photo = models.ImageField(upload_to="images")

Step 6 : Create a Form

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

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

class ImageFileUploadForm(forms.ModelForm):

    photo = forms.ImageField(label=_('Choose Image'),required=True, error_messages = {'required':'The image field is required.','invalid':_("Image files only")}, widget=forms.FileInput(attrs={'class': 'form-control custom-file-input','id' : 'customFile'}))
    class Meta:
        model = Image
        fields = ('photo',) 
Step 7 : Creating the Views

In this step, we need to create the views for performing ajax image upload to the database.Open the core/ file and add.

from django.shortcuts import render
from django.http import JsonResponse
from .forms import ImageFileUploadForm

# Create your views here.
def ajaxImageUpload(request):
    if request.is_ajax() and request.method == 'POST':
       form = ImageFileUploadForm(request.POST, request.FILES)
       if form.is_valid():
           return JsonResponse({'success': True, 'message': 'Image Uploaded Successfully!'})
           return JsonResponse({'error': True, 'errors': form.errors})
        form = ImageFileUploadForm()
        return render(request, 'index.html', {'form': form})
Step 8 : Creating the Templates

So, finally we are here to this step we need to creating django templates following below file:

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>
    <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">
                        <h4>Django Ajax Image Upload Example - <span class="text-primary"></span></h4>
                    <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 %}
                             <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 "image-upload" %}',
            type: 'POST',
            data: formData,
            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);
            cache: false,
            contentType: false,
            processData: false
Step 9 : Creating URLs

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

from django.urls import path
from . import views

urlpatterns = [
    path('image-upload/', views.ajaxImageUpload, name="image-upload"),

Next, we will require the modify the your root preoject folder lets update the file.

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

urlpatterns = [
    path('', include('blog.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 runserver

Next, go to the address with a web browser.


I Hope It will help you....