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?
source share