Django Ajax Image Upload Example

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 ProjectIn 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 exampleStep 2 : Create a App
python3 manage.py startapp coreStep 3 : Update setting.py
Here, do not forget to register the new app in the settings.py file. Under installed apps, just add ‘core’ to the list:
.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ]Step 4 : Database Setup
Next step, we will modify the settings.py file and update the database settings to configure the mydb database:
settings.pyDATABASES = { '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 core/models.py 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 form.like 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/views.py file and add.
core/views.pyfrom 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(): form.save() return JsonResponse({'success': True, 'message': 'Image Uploaded Successfully!'}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: 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:
core/templates/index.html<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <title>Tuts-Station.com</title> </head> <body> <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">Tuts-Station.com</span></h4> </div> <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> </div> </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> <div class="row mt-4"> <div class="col-lg-12 text-center"> <button class="btn btn-primary">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> /*------------------------------------------ -------------------------------------------- Custom File Input -------------------------------------------- --------------------------------------------*/ $(".custom-file-input").on("change", function() { var fileName = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label").addClass("selected").html(fileName); }); /*------------------------------------------ -------------------------------------------- Ajax Image Upload -------------------------------------------- --------------------------------------------*/ $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var formData = new FormData(this); $.ajax({ url: '{% url "image-upload" %}', type: 'POST', data: formData, success: function (response) { $('.error').remove(); if (response.success) { $('.success-msg-main').css('display', 'block'); $('.success-msg').text(response.message); }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 }); }); </script> </html>Step 9 : Creating URLs
In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom django.urls import path from . import views urlpatterns = [ path('image-upload/', views.ajaxImageUpload, name="image-upload"), ]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), 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 manage.py runserver
Next, go to the address with a web browser.
http://localhost:8000/image-upload/
I Hope It will help you....