0

I want to post a csv file to django view using jquery

<form  id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>


js is:

function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
  type: 'POST',
  url:'/list/create/',
  cache:false,
  dataType:'json',
  data:data,
  success: function(result) {
     console.log("ok")
    }
 });*/
}


django views.py:

def createlist(request):
    if request.method == 'POST':
        file =  request.FILES


here not getting file.
I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success. Clearly i want that file in views.py by request.FILES

5
  • 1
    you're missing form's param enctype="multipart/form-data" Commented May 28, 2014 at 12:52
  • @yedpodtrzitko now also print request.FILES['ListName'] gives <MultiValueDict: {}> Commented May 28, 2014 at 12:57
  • well... the thing is you can't upload file via AJAX. You have to use iframe (I've some library for this purpose here: github.com/yedpodtrzitko/ajax-uploader ) Commented May 28, 2014 at 13:00
  • Actualy this question is answered here: stackoverflow.com/questions/5392344/… Commented May 28, 2014 at 13:00
  • @yedpodtrzitko there using form action as url Commented May 28, 2014 at 13:05

2 Answers 2

1

When uploading files, your form must have this attribute:

enctype='multipart/form-data'

like this:

<form  id="form" enctype='multipart/form-data'>

This might help you understand.

Sign up to request clarification or add additional context in comments.

1 Comment

Then also print request.FILES gives <MultiValueDict: {}>
0

You have to use a FormData object and a slightly modified version of basic ajax post:

    var data = new FormData();
    var file = null;

    //when uploading a file take the file
    $("#your-file-input-id").on("change", function(){
        file = this.files[0]
    });

    //append the file in the data
    data.append("file", file);

    //append other data
    data.append("message", "some content");

    $.ajax({
        url: '/path',
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        success: function (data, status, xhr) {
            //handle success            },
        error: function (data, status, xhr) {
            //handle error
        }

    });

In Django you will find the file in request.FILES['file']. I hope this is helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.