I am encountering an issue when trying to send an image using an AJAX request to Django. Below is the HTML code I am using:
<form>
<input type="file" id="files" name="image">
</form>
Next, here is the corresponding JavaScript code:
var control = document.getElementById("files");
var p = {
title: $('input[name=title]').val(),
subtitle: $('input[name=subtitle]').val(),
content: $('textarea#article-content').val(),
image: files[0],
};
$.ajax({
url: '/prive/nouveau-projet',
type: "POST",
data: JSON.stringify(p),
crossDomain: true,
success: function() {
window.location.href = '/prive/projets/';
},
error: function() {
console.log("error");
}
});
Finally, below is the server-side code snippet for handling the request:
if request.method == "POST":
data = request.POST.keys()[0]
dataJson = json.loads(data)
p = Projet(title=dataJson['title'], subtitle=dataJson['subtitle'], content=dataJson['content'], image=dataJson['image'])
p.save()
return HttpResponse()
This implementation results in errors related to dataJson['image']
. Can anyone provide guidance on how to resolve this issue? Thank you.