I’ve strange behavior on my current project (media and media_root folders) didn’t create and also the image path is strange it is like(“C:\fakepath\v6 wallpaper.jpg”), but it saved successfully to database …
I’ve many forms saved together at the same time … I tried many things to fix this issue but I failed I know that I miss something but I don’t know what is it?,
I tried one of my old projects that I developed on Windows OS to compare if I miss something but it is the same except in my old project I save (one image at once) but in my current project (I save list of images at once) also I use AJAX here but on my old project I haven’t used it .
I tried to save and upload images to its database (it works normally) I removed the (media_root folder) and it creates itself again normally .
Here are lines of my code on my current project
MY MODELS
let imageValues = $('.image-value').map(function() {
return $(this).val();
}).get();
data :{
// for image form
'img-photo': $('#id_img-photo').val(),
'images-list': imageValues,
}
I think we’d need to see the rest of the page and JavaScript that you are running here. I don’t see enough yet to begin to diagnose this, and it’s not really clear to me exactly what you’re trying to do.
If you’re attempting to upload files and not just file names, see File Uploads | Django documentation | Django for details as to how Django expects to see uploaded file data. What was helpful for me to learn how it works was to create a very simple example of a file upload, and then look at the data being posted in the browsers developer tools as well as looking what was received by Django in the request object. (request.POST and request.FILES)
If you’re doing the file uploads using AJAX, you could also consider creating a JSON object with the file data to submit.
After investigating the insertion of image of the (ProductImage model). It is working good (without using Ajax)
the images created and the function(photo_path) works good, It gives me the URL in the database as (images/60/462d/60.jpeg) and send it to (media_root folder).
But when using Ajax (request.FILES[‘photo’]) doesn’t work and gives me “None” and the following url saved in the database (“C:\fakepath\pepsi.jpeg”) … I’m trying to use [ if request.accepts("*/*") ] instead of [ if request.accepts("text/html")] but it didn’t work
I don’t know how to fix it till now , But I’m still searching to find a good solution to image issue
Note that request.FILES will only contain data if the request method was POST , at least one file field was actually posted, and the <form> that posted the request has the attribute enctype="multipart/form-data" . Otherwise, request.FILES will be empty.
You have:
which isn’t going to work to supply data to request.FILES.
(There may be other things wrong as well, but this is the first item that I noticed.)
Thanks for your help, I appreciate it so much .
I’ve tested using Ajax with simple function (it has only one image field), It’s doing the same behavior with (“contentType: false”) and it’s not working and no image created in media_root folder. Without Ajax code the normal behavior occurs and the uploading process creates image via Django normally in the media_root folder
def add_test_image(request, product_id):
data = {}
data['error'] = 'Error !!!'
data['type'] = 'error'
if request.method == 'POST': #request.accepts('text/html') and
img_files = request.FILES.get('photo')
img_post = request.POST.get('photo')
print(
'MY-IMAGE-PHOTO-FILES: ', img_files,
'MY-IMAGE-PHOTO-POST: ', img_post
)
img_form = ProductImageForm(
request.POST or None,
request.FILES or None
)
if img_form.is_valid():
img_save_form = img_form.save(commit=False)
img_save_form.product_id = product_id
# img_save_form.photo = request.FILES['photo']
img_save_form.save()
print('IMAGE FORM IS VALID AND IMAGE SAVED DONE ...',
request.FILES['photo'])
data['error'] = 'IMAGE FORM IS VALID AND IMAGE SAVED DONE ...'
data['type'] = 'success'
return JsonResponse(data)
# return redirect(reverse(
# 'test_image_details', args=(product_id,)
#))
else:
print('IMAGE Form Is Invalid !!!')
else:
img_form = ProductImageForm()
context = {
'img_form': img_form,
'product_id': product_id
}
return render(request, 'home/add_test_image.html', context)
$(document).on('submit', ".image-form", function (e) {
e.preventDefault();
let productID = '{{product_id}}';
let imageValues = $('.image-value').map(function() {
return $(this).val();
}).get();
console.log(
'imageValues::', imageValues,
'img-photo::', $('#id_photo').val(),
);
$.ajax({
type: 'POST',
url: '{% url "add_test_image" product_id=0 %}'.replace('0', productID),
cache: false,
contentType: false,
processData: false,
data: {
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
// for image form
'photo': $('#id_photo').val(),
'images-list': imageValues,
},
success: function (data) {
console.log(
'WHAT IS GOING ON HERE FROM SUCCESS: ',
'IMAGE-PHOTO:::: ', $('#id_photo').val(),
);
$(function() {
var Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
if (data['type'] == 'error'){
console.log(data['type'])
toastr.error(data['error']);
} else if (data['type'] == 'success') {
toastr.success(data['error']);
} else if (data['type'] == 'info') {
toastr.info(data['error']);
}
});
},
error: function (){
console.log('ERROR with ajax request');
},
});
e.preventDefault();
});
What attribute should I use in Ajax request to treat normally with image field and return correct data not “None” as request.FILES['photo'] and as request.FILES.get('photo')
But it didn’t fix my issue…
Now I’m using request.accepts('*/*') but it didn’t fix the issue …
I will try to use the FormData() object as mentioned in the threads , and see if it is useful or not.
I will try to use the FormData() object as mentioned in the threads , and see if it is useful or not.
FormData() object fixed it and another missing thing (To get the value of an file field input you must use $('#image').get(0).files[0] NOT $('#image').val() It’s very very important)
Also FormData() enable me to insert multiple rows of a form in the same time,
This is my code if anyone experience this issue with ajax
$(document).on('submit', ".product-form", function (e) {
e.preventDefault();
let formData = new FormData();
formData.append('pro-branch', $('[name=pro-branch] option:selected').val());
formData.append('pos_station', $('[name=pro-pos_station] option:selected').val());
// IMG-FORM
let imageValues = $('.image-value').map(function() {
return $(this).get(0).files[0]; // instead of using $(this).val()
}).get();
// because I have many rows of img_form
if(imageValues.length){
for(let image of imageValues){
formData.append('img-photo', image);
}
}
let token = '{{ csrf_token }}';
$.ajax({
type: 'POST',
url: '{% url "products:add_product" %}',
headers: {'X-CSRFToken': token},
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (data) {
console.log(
'SUCCESS: ');
},
error: function (){
console.log('ERROR with ajax request');
},
});
e.preventDefault();
});
Sorry I can’t absorb what do you mean ?, But really thank you for your time and efforts