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?