-2

I created form upload file in django. it is working. But when i try with ajax in django file upload is not working.

My code:

models.py

class Upload(models.Model):
   documents = models.FileField(upload_to=content_file_name)
   user = models.ForeignKey(User)

class Meta:
    app_label = 'documentapp'

forms.py:

from django import forms
class UploadForm(forms.Form):
    documents = forms.FileField()

html:

<input type="file" name="documents" id="documents" class="form-control" required="required""/>
 <input type="button" id="upload_file_button" required="required" value="Upload" onclick="UploadUserDocuments()"/>

ajax in same html file:

function UploadUserDocuments() {
    $.ajax({
        url: "/signup/upload/",
        type: "POST",
        data: {
           documents:$('education_documents').val(),     
        },
        success: function(response){
        }
    });
}

view.py

def upload(request):
context = RequestContext(request)
if request.method == 'POST':
    form = UploadForm(request.POST, request.FILES)
    if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
    return HttpResponse('true')
else:
    return HttpResponse('GET')

handle_uplaoded_fiel.py

def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
    for chunk in f.chunks():
        destination.write(chunk)
Balakrishnan
  • 266
  • 2
  • 5
  • 16

2 Answers2

1

There are several problems with the HTML/JS.

  • The first line of your HTML has a double terminating quotation for the value of the required attribute.

  • Your UploadUserDocuments() function does the following:

    $('education_documents').val()

    which is attempting to match an element such as <education_documents> rather than the usual way of selecting the value of an element by its id (i.e. using the # selector).

However, it's more involved to perform a file upload using JQuery. This answer has some ideas: How can I upload files asynchronously?

Community
  • 1
  • 1
Ben Rowland
  • 361
  • 1
  • 5
0

It seems that you don't send csrf_token. You can skip it for you view(which is not really recommended) by using csrf_exempt decorator.

Otherwise you should add {%csrf_token%} tag to your template. It will create hidden field with CSRF token. The way how to handle it in AJAX you can find in official documentation.

Also I'm curious why don't you render form from variable, but add HTML manually instead - but it isn't directly related to the topic.

So I'd to do it like: html:

<form id="upload_doc" action="/signup/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} 
   {{form}}
   <input type="submit" value="send">
</form>

Also please see notices from @Ben Rowland answer

Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54