extending from my previous post containing problems with django and ajax (Django Ajax Image submit), I came, as mentioned in the EDIT, to the following situation:
My jquery/ajax call:
<script>
$(document).ready(function () {
// This jquery changes the appearance of the django { form_image }
var imgElement = $('#id_image');
imgElement.css('visibility', 'hidden');
console.log($('#id_image').attr('type'))
// This function triggers the hidden submit,
// which triggers the ajax image request
imgElement.on({
change: function () {
$('#hidden-submit-img').click();
},
});
});
// This jquery is for the ajax post of the image
// Doing it with submit, the image wont get saved, but the request is "success"
// $('#image_form').submit(function (event) {
// Doing it with change, the image gets saved successfully, but the respond loads a new page
$('#image_form').change(function (event) {
event.preventDefault();
$.ajax({
data: {
image: $('#id_image').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
enctype: $(this).attr('enctype'),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
console.log(1);
},
error: function () {
console.log(0);
}
});
});
</script>
As described in the comments there is this strange behaviour, either the page wont get reloaded but the image doesnt get saved, or the image gets saved but the page renders to a white page only containing "success". I can see, that the console.log(1) actually executes, and THEN the white page gets loaded.
I tried to keep my files as simple as possible.
Here is my view in views.py:
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
ImagesUpload.objects.create(
image = image,
)
return HttpResponse('success')
models.py:
class ImagesUpload(models.Model):
image = models.ImageField(upload_to=renaming_file)
def __str__(self):
return str(self.image)
home.html:
<form id="image_form" method="post" enctype="multipart/form-data" action="{% url 'website:image-feedback' %}">{% csrf_token %}
<button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button>
{{ form_image.image }}
<input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden">
</form>
I think I am close to the solution but maybe my skills are insufficient.
I want to upload an Image, store it in my database and keep my website going without reloading/refreshing.