Drag and drop images with Django, XMLHttpRequest and vanilla js by Toumi Abderrahmane


hey yes you prepare yourself to create an image drag and drop and add it to your Django project using pure javascript and Django forms for validation

first of all, if you want to start where I’m, you need to download this basic app from this link


/////// THE AJAX PART ////////////////////

  ///////////// get cookie /////////////////
function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          // Does this cookie string begin with the name we want?
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  return cookieValue;
var csrftoken = getCookie('csrftoken');
button = document.getElementsByTagName('button')[0]

  button.addEventListener('click', event=>{
    var xhttp = new XMLHttpRequest();
    formData = new FormData()
    formData.append('image', document.getElementById('id_image').files[0])

    xhttp.open("POST", '/', true);
    xhttp.setRequestHeader("X-CSRFToken", csrftoken);

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            data = JSON.parse(this.responseText)



im using getCookie to generate a csrf token because Imposes on us to use csrf token with post request Django Part 🐍🐍 :

first of all, you need to add a submit button inside the image form, (look at the code below)


        <button type="submit">submit</button>
#add this imports
from django.http import JsonResponse
from .models import ImageModel

def image(request):
    form = ImageForm()
    if request.method== "POST":
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            return JsonResponse( {'details': "image saved  successfully"})#new
        else :
            data = {'details': form.errors}
            return JsonResponse(data)#new

    return render(request, 'image/index.html', {'form':form})