Drag and drop images with Django, XMLHttpRequest and vanilla js by Toumi Abderrahmane ¶
See also
Description ¶
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
Code ¶
/////// 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));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
button = document.getElementsByTagName('button')[0]
button.addEventListener('click', event=>{
event.preventDefault()
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.send(formData)
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText)
console.log(data)
}
}
})
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)
{{form.image}}
</div>
</div>
<button type="submit">submit</button>
</form>
....
#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():
ImageModel.objects.create(image=form.cleaned_data.get('image'))#new
return JsonResponse( {'details': "image saved successfully"})#new
else :
data = {'details': form.errors}
return JsonResponse(data)#new
return render(request, 'image/index.html', {'form':form})