[Answer]-Post file using jquery in Django

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.

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.

Leave a comment