简体   繁体   中英

Uploading a file through AJAX with a Django Form

I've been trying to create a system that allows uploads of text and a file through my Django form. Whenever I try post the form I can only seem to get the message part of the form. I've been following this answer for reference but I've been running into trouble. First, my form looks like this:

class MessageForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea, required=False)
    file = forms.FileField(label="Attachment", required=False)

and it's rendered to HTML like this:

<form id="message-form" enctype="multipart/form-data">
    {{form.message}}<br>
    {{form.file}}

    <div class="sectio4-bottom">
        <div class="right-bottom">
            <input id="send-button" type="submit" value="Send"/>
        </div>
    </div>
</form>

The current version of my JS function I'm working with looks entirely like this:

$('html').on('submit', '#message-form', function(e){
    e.preventDefault();
    var data = new FormData($('#message-form').get(0));
    $.ajax({
        url: '#',
        type: 'POST',
        data: {
         'data': data,
         'csrfmiddlewaretoken': $('.csrftoken').text()
        }
    });
    return false;
})

but the part I'm interested in is var data = new FormData($('#message-form').get(0)); . I got this from the linked question but when it runs it gives me an empty object. I've also tried passing the data as 'data': $('#message-form').serialize() but when it gets to the backend and I look at request.POST I see that the only thing included in data is the message I send. request.FILES is empty.

How can I access the specified file?

Try adding:

data.append('file',$("#file").files[0]); #Assume 'file' is id of your file field

after

var data = new FormData($('#message-form').get(0));

Here an example function that I'm using

function saveVeichle() {
    $(".sk-wave").show();
    var dati = new FormData();
    dati.append('csrfmiddlewaretoken','{{csrf_token}}');
    dati.append('note',$("#note").val());
    dati.append('dip',$("#dip-0").val());
    dati.append('stato',$("#stato").val());


    $("input").each(function(id,obj){
        if (obj.type == 'checkbox') {
            dati.append(obj.name,obj.checked);
        } else {
            dati.append(obj.id,obj.value);
        }
    });

    dati.append('foto',$(".foto")[0].files[0]);
    dati.append('libretto',$(".libretto")[0].files[0]);
    $.ajax({
        url: "/mezzi/api/salva_mezzo/",
        type: "POST",
        data: dati,
        cache: false,
        contentType: false,
        processData: false,
    }).done(function(data) {
        if (data.res == 'ok') {
            window.location = '/mezzi/' + data.id + '/';
        } else {
            if (data.errors) {
                for (d in data.errors) {
                    noty_alert(d + ":" + data.errors[d]);
                }
            } else {
                noty_alert('Errore Salvataggio Mezzo!');
            }
            $(".sk-wave").hide();
        }

    });
}

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