0

How exactly do I upload a file using an ajax call ? My form in template

<form action="images/" enctype="multipart/form-data" method="POST" class="upload">                                            
    <table>
        {{ form.as_table }}
        <td><input type = "button" onclick="" value="Upload" id = "test"/</td>
    </table>
</form>

My jQuery function :

$(document).ready(function(){
    $("#test").click(function(){
        var string = $("form.upload").serialize();
        alert(string);
        $.ajax({
            url :'/test/',
            type:'post',
            data: {datas:string},  
        dataType: "json",           
         success: function(response) {
                    alert(response);
                  }
        });
    });
});

My view :

@csrf_exempt        
def test(request):
    if request.is_ajax():
        form = ImageUploadForm(request.POST)
        if form.is_valid():
            form.save()
        return HttpResponse("Saved !!!!")

Here I have the view for the file upload but the file does not appear in the form variable in the django view . What should I do to get the file in the view ? The form has a filefield for uploading . It is a model form.

1 Answer 1

4

2 important pieces are missing here:

  1. jQuery.serialize() doesn't do anything to file fields. Check out jQuery form plugin for a robust method of posting form with files via Ajax
  2. You need to explicitly pass the uploaded files to the form constructor: form = ImageUploadForm(data=request.POST, files=request.FILES)
Sign up to request clarification or add additional context in comments.

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.