简体   繁体   中英

Upload file using jQuery ajax with Django

I am learning ajax and JQuery with Django. I created a basic app to update the text field but now I added the file field. But unable to make it work.

The is model class

class TextModel(models.Model):
    text=models.CharField(max_length=200)
    file=models.FileField(upload_to='files')

This is my template

<div class='col-8 mt-5'>
    <form method='POST' id='formCreated' data-url="{% url 'home' %}" enctype="multipart/form-data">
        <!-- data-url is used in ajax function -->
        {% csrf_token %}
        {{ form.as_p }}
        <button type="button" id="btn_submit">Upload</button> 
    </form>
    </div>
    
    <div class='col-5 mt-5' id='resultid'> 
    </div>

Here is my views function

def home(request):
    if request.method=='POST':
        form = TextForm(request.POST,request.FILES)
        if form.is_valid():
            out=form.save()
            return JsonResponse({'text':model_to_dict(out)},status=200)
        else:
            return render(request,'home.html',{'form':form})
    else:
        form = TextForm()
        return render(request,'home.html',{'form':form})

Here is my code in js file

$(document).ready(function(){

    $('#btn_submit').click(function()
    {
        var serializedData=$('#formCreated').serialize();
        console.log(serializedData)


        $.ajax({
            url:$("formCreated").data('url'),
            data:serializedData,
            type:'POST',
            success:function(response){
                // reponse recieved from views recieved here and sent to div with resultid in home.html
                console.log(response)
                $('#resultid').append(response.text.text)
                // first text is key of response and second text is the text object
            }
        })

        $('#formCreated')[0].reset();
    });

});

This is the error I am getting

file.js:16 Uncaught TypeError: Cannot read property 'text' of undefined
    at Object.success (file.js:16)
    at c (jquery.min.js:3)
    at Object.fireWith [as resolveWith] (jquery.min.js:3)
    at k (jquery.min.js:5)
    at XMLHttpRequest.r (jquery.min.js:5)

The file.js is the file where above js code is.

This is the solution I found working

$(document).ready(function(){
    $('#btn_submit').click(function()
    {
        console.log('button clicked')
        var form = $('#formCreated');
        var formdata = false;
        if (window.FormData){
            formdata = new FormData(form[0]);
        }
        var formAction = form.attr('action');
        $.ajax({
            url         : $("formCreated").data('url'),
            data        : formdata ? formdata : form.serialize(),
            cache       : false,
            contentType : false,
            processData : false,
            type        : 'POST',
            success:function(response){
                // reponse recieved from views recieved here and sent to div with resultid in home.html
                console.log(response)
                $('#resultid').append(response.text)
                // first text is key of response and second text is the text object
            
            }
        });
    });

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM