Reputation: 63
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.
Upvotes: 2
Views: 832
Reputation: 1221
your html form
<form id="image_form"> #does not provide any attribute
{% csrf_token %}
{{ form_image.image }}
</form>
jquery put jquery in same page where your form
<script>
$("#id_image").change(function(){ // here my second change apply id of image field
var formdata = new FormData(); //create formdata object
formdata.append('image',this.files[0])
formdata.append('csrfmiddlewaretoken',$('input[name=csrfmiddlewaretoken]').val()); //apply csrf token
$.ajax({
url:"{% url 'website:image-feedback' %}",
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
//update src attribute of img tag
$('#profile_pic').attr('src',data.url);
$('#image_form').trigger('reset'); // This reloads the form for additional upload
},
error:function(error){
//display error base on return the view
alert(error.error)
}
});
return false;
});
</script>
your view
def image_feedback(request): # url 'website:image-feedback'
if request.method == 'POST':
image = request.FILES.get('image')
img = ImagesUpload.objects.create(
image = image,
)
return JsonResponse(status=200,data={"url": img.url}) #return json response
else:
return JsonResponse(status=203,data={"error": "unauthorized request.!!"})
I give a lot stuff you see and apply in your code then open firefox browser see in network tab of inspect element return you status code see which status code return and let me know if any error
Upvotes: 2