featured-ajax.jpg

How to GET and POST images Asynchronously using AJAX in Django — in Detail

Jaya Shankar Bandaru
4 min readJun 19, 2020

--

Hey Guys 👋 ,

I am Jaya Shankar, a Coding enthusiast, last week I was working on a project related to building a website using Django in my project I needed to send and request Images asynchronously (basically chatting application). I googled🔎 to learn it but I couldn’t find everything in one place so I decided to write this article now let’s get our hands dirty💻

I assume that whoever reading this article has some basic knowledge in Python, Javascript and Django Framework, let’s get started

Modifying settings.py

The first thing we do whenever we need to use images in the Django project is to set MEDIA_ROOT & MEDIA_URL just copy the below code and paste it in your settings.py file

MEDIA_URL=’/media/’MEDIA_ROOT=os.path.join(BASE_DIR,’media’)

Just to give more sense the next section is the code that I wrote which is needed to move further

and also add the following line in urls.py so it can know where the media files are located

if its first time for you to add MEDIA_URL then I would suggest to take the above code and look where the images are being saved

urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

models.py

from django.db import models
class ImageUpload(models.Model): image_file=models.ImageField(upload_to=”images”)

This is a basic Django model I created which has only one field (‘ImageField’)

here we use upload_to option to specify a subdirectory of MEDIA_ROOT to use for uploaded files.

forms.py

from django import forms
from .models import ImageUpload
class ImageForm(forms.ModelForm): image_file=forms.ImageField(widget=forms.FileInput(attrs={"id" : "image"})) class Meta: model=ImageUpload
fields= [
'image_file' ,
]

The above one is a basic form for the ImageUpload model we just created

it's a good practice to use forms if you are not familiar my advice is to learn them because they make our work more easy

views.py

from django.shortcuts import renderfrom .forms import ImageForm
from .models import ImageUpload
def index_view(request): newForm= ImageForm()
context={"form" : newForm ,}
return render(request,"index.html",context)

For now views.py as only one function(index_view) whose sole purpose is to create ImageForm object and render it in ‘index.html

index.html

<!DOCTYPE html>
<head>
{% load static %}
<title>Home</title> <script src="{% static 'jQuery.js' %}" type="text/javascript
</script>
<script src="{% static 'index.js' %}" type="text/javascript">
</script>
<style>
.imageSize {
height: 100px;
width: 100px;
}
</style>
</head>
<body> <form method="POST" enctype="multipart/form-data" id="imageForm"> {% csrf_token %}
{{form.as_p}}
<input type="button" id="submit" value="submit">
</form> <button id="showImages">ShowImages</button> <div id="imageField"></div></body>

Here we added two buttons(#submit,#showImages) for which we will be writing functions later and be sure to set the form enctype=“ multipart/form-data” and include csrf_token

A screengrab of the rendered HTML:

screenGrab-1

now let’s write some JavaScript to upload images to the server via AJAX to keep things simple I am using JQuery for AJAX so be sure to include JQuery script in your HTML

To Upload Images to Server:

In index.js

we will be uploading images only when a user clicks submit button

document.getElementById("imageForm").onclick=function(){

$.ajax(
{
url : '/add_image' ,
method : 'POST' ,
data : new FormData(imageForm) ,
processData: false,
contentType: false,
})
};

-> processData is set to false so that JQuery Lib does not stringify the data

FormData is an object to represent HTML form data.

make sure to add the route to ‘/add_image’ in urls.py

At the end of this article, you can find my ‘urls.py’ file

Now let’s go to our views.py where we will be writing code to store the uploaded images into the database

In views.py

def addImage_view(request):   form=ImageForm(request.POST,request.FILES)   if(form.is_valid()):
form.save()
return HttpResponse("success")

To Request Images from Server :

In index.js

document.getElementById("showImages").onclick=function(){    $.ajax(
{
url : '/get_images' ,
method : 'GET' ,
success : function(data){
imageField=document.querySelector("#imageField") for(let i=0;i<data.image_urls.length;i++){
imageField.appendChild(CreateImage(data.image_urls[i]))
}
}
});
}
function CreateImage(src)
{
let img = document.createElement("img")
img.src =src
img.className="imageSize"
return img;
}

we will be making AJAX request for images when a user clicks ‘ShowImages’. button

now let’s write code in views.py to handle the request

def getImages_view(request):    images=ImageUpload.objects.all()
image_urls=[]
for image in images:
image_urls.append("media/"+str(image.image_file))
response={"image_urls" : image_urls}
return JsonResponse(response)

here in the above function first we get all the images as QuerySet and store them in ‘images’ and then since we need only where the images are located (URL) so we append all the URLs into a list (image_urls) and return the data as JSON to the client

if we go to the JS we can see on success(getting back a response) the success function gets executed in the just function we are just appending the images into the HTML file

A ScreenGrab after clicking ShowImages :

urls.py

The below file is part of the one of the apps folder

from django.urls import pathfrom django.conf.urls.static import static
from django.conf import settings
from .import viewsurlpatterns = [ path('',views.index_view,name="home"),
path('add_image', views.addImage_view , name="add_image") ,
path('get_images', views.getImages_view , name="get_images")
]urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

My apologies for not including error handling because I wanted to keep the code as short as possible ✌️

if you have any doubts and found any errors /better way to do in code please mail me: bjayashankar2102@gmail.com

if you are interested in looking at the code: click here

--

--