I don't understand how to integrate jQuery plugins with my Ajax function to post a Django form. I have seen examples dealing with only one field, the file to upload. But what if my form contains other fields (textbox, select, etc.)?
Here is my html form (I have a drop down list and a file to upload):
<form id="import_form" class="form-horizontal" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.non_field_errors }}
<div id="fileToImportChoice" class="fieldWrapper">
{{ form.fileToImport.errors }}
{{ form.fileToImport }}
</div>
<div id="file_to_import" class="fieldWrapper">
{{ form.csvFile.errors }}
{{ form.csvFile }}
</div>
<input type="button" id="import_button" value="IMPORT" onclick="javascript:display_message('{% url import %}', document.getElementById('import_form'))" />
</form>
Here is my jquery function:
function display_message(link, form)
{
var datastring = $(form).serialize();
$.ajax(
{
url: link,
type: 'POST',
dataType: 'json',
enctype: "multipart/form-data",
data: datastring,
success: function(result)
{
//form not valid -> displays errors
if (result.form_errors)
{
//append current errors to the html form
errors=result.form_errors
for (var key in errors)
{
$("#"+key+"_errors").html('<ul class="errorlist"><li>'+errors[key]+'</li></ul>');
//~ alert(key+': '+errors[key]);
}
}
else
{
}
}
});
}
First question: should I insert the name of the file in my datastring
variable? For the moment, each time I display the form errors, Django complains that my csvFile
is empty, even If I have previously selected a file to upload. I guess it's normal with no plugin. Right?
Now, my main question: how to integrate jQuery plugins with my function? I have seen a simple one called Simple-Ajax-Uploader
.
Here is an example of how to use it:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
So finally... how to send the file data along with the other data of my form? My idea is to call the plugin in my display_message
function and then update my datastring
variable that contains all the data to post to my view. If so, how?
EDIT:
I am looking for a simple plugin, just one file to upload, no need for custom css. And I want it portable (so HTML5
and FormData
is excluded).