As the title suggests, here is the code before any further explanation.
{% extends 'informations/userpage.html' %}
{% load static %}
{% block redaction %}
<div class="redaction">
<form method="POST" enctype="multipart/form-data" action="/redaction/" class="article-post">
{% csrf_token %}
<div class="article-picture">
{% if article.image %}
{{article.image}}
{% else %}
<img class="generic-image" src="{% static 'informations/images/none-picture.svg' %}" alt="Image article">
{% endif %}
<img class="edit" id="article-image" src="{% static 'informations/images/edit.svg' %}">
</div>
<div id="id01" class="modal" style="display: none;">
<div class="upload-container">
<input type='file' name="newImage">
<div class="button" id="uploadImage" name="upload" value="envoyer">Envoyer</div>
</div>
</div>
</form>
{% csrf_token %}
<script id="picturesend">
var csrf_token = document.getElementsByName('csrfmiddlewaretoken').value
</script>
<script type="text/javascript"
id="django-admin-popup-response-constants"
src="{% static 'informations/redaction.js' %}">
</script>
</div>
{% endblock %}
var articleImage = document.getElementById('article-image');
var uploadImage = document.getElementById('uploadPic');
uploadImage.addEventListener('click', displayUpload);
articleImage.addEventListener('click', displayUpload);
function displayUpload() {
var uploadfile = document.getElementById('id01');
var uploadPicture = document.getElementById('uploadImage');
uploadPicture.addEventListener('click', uploadFile);
uploadfile.style.display='block'
}
function uploadFile() {
var formData = new FormData();
var file = document.getElementsByName('newImage');
var image = document.getElementsByClassName('generic-image')[0];
formData.append('newImage', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/', true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
image.setAttribute('src',JSON.parse(xhr.responseText));
} else {
alert('An error occurred!');
}
};
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
xhr.send(formData);
}
My file model
def userDirectoryPath(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.username, filename)
class Media(models.Model):
user = models.ForeignKey(User, null=True , on_delete=models.CASCADE)
media = models.FileField(upload_to=userDirectoryPath)
My view handling ajax.
@login_required
def upload_media(request):
user = request.user
data = {}
if request.POST:
newFile = Media()
newFile.media = request.FILES['newImage']
newFile.user = user
newFile.save()
data.update({"media_url": newFile.media.url})
return JsonResponse(data)
With that said, I am looking to send files to my server without using jQuery, save them in the database, and return the URL through JsonResponse for further use with JavaScript.
As a beginner in these technologies, I understand that my code may not follow best practices, but I hope it's clear enough.
The issue I am facing is that upon checking the console log, I see an empty object {}. It seems that the POST method is not being properly recognized. I tried using if request.method == 'POST':
but the result is the same.
I suspect the problem lies in my JavaScript code, but as I am new to AJAX, I have not been able to find a solution without using jQuery.
If anyone has any suggestions or solutions, or knows where I can find help, I would greatly appreciate it. I am open to providing more details if needed. Thank you for your time and any assistance you can offer.
[UPDATE]
Although the condition request.method == "POST"
is true, I am encountering an error within the 'if' block with
MultiValueDictKeyError at /upload/ newImage
.
This error is reminiscent of when I forgot to add enctype="multipart/form-data"
within a <form>
. I am currently stuck at this point.