I’m trying to upload multiple images with ajax request, i’m using modelformset_factory
to upload several images , here is my code :
class Document(models.Model):
booking =models.ForeignKey(Booking,on_delete=models.PROTECT)
docs = models.ImageField(upload_to=upload_docs)
my forms.py
class UploadDocumentsForm(forms.ModelForm):
class Meta:
model = Document
fields = ['docs']
my views.py
@login_required
def add_new_image(request,id):
obj = get_object_or_404(Booking,id=id)
if request.is_ajax() and request.method == 'POST':
images = UploadDocumentFormSet(request.POST,request.FILES)
if images.is_valid():
for img in images:
if img.is_valid() and img.cleaned_data !={}:
img_post = img.save(commit=False)
img_post.booking = obj
img_post.save()
return JsonResponse({'success':'success'})
else:
messages.error(request,_('error message'))
images = UploadDocumentFormSet(queryset=Document.objects.none())
return render(request,'booking/add_img.html',{'obj':obj,'images':images})
and here is my template includes html and ajax
$('#addButton').click(function() {
var form_dex1 = $('#id_form-TOTAL_FORMS').val();
$('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1));
$('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1);
});
const formData = new FormData()
formData.append('csrf',document.getElementsByName('csrfmiddlewaretoken').value);
formData.append('docs0',document.getElementById('id_form-0-docs').files[0]);
formData.append('docs1',document.getElementById('id_form-1-docs').files[0]);
formData.append('docs2',document.getElementById('id_form-2-docs').files[0]);
formData.append('docs3',document.getElementById('id_form-3-docs').files[0]);
const form = document.getElementById('docs-uploader-form')
form.addEventListener("submit",submitHanler);
function submitHanler(e){
e.preventDefault();
$.ajax({
type:'POST',
url:"{% url 'booking:add_new_image' id=2222 %}".replace(/2222/,parseInt({{obj.id}})),
data:formData,
dataType:'json',
success:successFunction,
})
}
function successFunction(data){
// console.log(data)
form.reset();
alertify.success('added new image')
}
<button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl">
{% trans "add new image" %}
</button>
<form action="" method="POST" enctype="multipart/form-data" dir="ltr" id="docs-uploader-form">{% csrf_token %}
{% for form in images.forms %}
{{form.id}}
{{images.management_form}}
<div class="form-group mt-3" id="images">
{{ form.docs | add_class:'form-control-file' }}
</div>
{% endfor %}
<div class="form-group mt-3" id="formset" style="display: none;">
{{ images.empty_form.docs | add_class:'form-control-file' }}
</div>
<button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "submit" %}</button>
</form>
is there something i have to change please or isnt there a better to achieve it please ? thank you in advance . i much appreciate your helps ..
2
Answers
you have to get the files like this :
In your ajax code, you missed setting the contentType and processData to false, this is needed when you use a FormData object with jQuery.ajax