How to upload a file using Ajax on POST?

I know that topics on this topic have not been missed, so I looked into a huge number of posts about this topic and could not find something that suited me, so I try to build it myself.

All I want to do is upload the file using Ajax with Django to avoid page refresh.

Here is what I did:

basic_upload.html:

<form method="post" id="creationOptionsForm" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form.name.errors }} {{ form.name }} </div> <div> {{ form.email.errors }} {{ form.email }} </div> <div> {{ form.logo.errors }} {{ form.logo }} </div> <input type="submit" value="submit"> </form> 

Ajax.js:

 $(document).on('submit', '#creationOptionsForm', function(e){ e.preventDefault(); var form_data = new FormData(); form_data.append('file', $('#creationOptionsForm').get(0).files); $.ajax({ type:'POST', url:'/designer/results/', processData: false, contentType: false, data:{ organisation:$('#id_organisation').val(), email:$('#id_email').val(), logo:form_data, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, }); }); 

Views.py:

 def creationResult(request): if request.method == 'POST': form = UserInfos(request.POST, request.FILES) if form.is_valid(): photo = form.save() ... ... 

(forms.py and urls.py are correctly configured, there is no need to include them).

I assume that the problem is with the way I do on ajax.js , since on debug (pdb) request.POST returns all data except logo .

What am I doing unchanged?

+5
source share
1 answer

The method below works for me, it will pass all form values ​​as serialize() . You will receive an input of all forms inside request.POST and the request.FILES logo

Try the following:

 $(document).on('submit', '#creationOptionsForm', function(e){ e.preventDefault(); var form_data = new FormData($('#creationOptionsForm')[0]); $.ajax({ type:'POST', url:'/designer/results/', processData: false, contentType: false, async: false, cache: false, data : form_data, success: function(response){ } }); }); 

Update:

basically async:false will execute an ajax request and stop executing further js code until the time request is complete, because it may take some time to download the file to download.

While cache will cause the browser not to cache downloaded data to get updated data in ajax request

The official documentation is here

+9
source

Source: https://habr.com/ru/post/1269132/


All Articles