Question

I have a form which includes filefield to upload some files. Sometimes what happens is at first, I select one file from browse to upload but then i realize i do not want to upload it anymore.How can i make it empty again?? Is it like that once this field is filled it cannot be reverted back to empty??

Thanks in advance

Was it helpful?

Solution

This can be accomplished with javascript.

Quoting Clear upload file input field with jQuery post from electrictoolbox.com:

function reset_html(id) { $('#'+id).html($('#'+id).html()); }

$(document).ready(function() {

var file_input_index = 0;
$('input[type=file]').each(function() {
    file_input_index++;
    $(this).wrap('<div id="file_input_container_'+
                  file_input_index+'"></div>');
    $(this).after('<input type="button" value="Clear" 
                   onclick="reset_html(\'file_input_container_'+
                                         file_input_index+'\')"
                   />');
});

});

OTHER TIPS

If you try to post an un-validated form, when you re-render the form, the filefield will be empty.

See this issue for more explanation.. Django Form File Field disappears on form error

The following works for me. Add a clear button to your html

<input type="submit" name = "submit-clear" value="clear file">

Then in your view handle this button using..

if 'submit-clear' in request.POST:
    return HttpResponseRedirect('')

This should clear any filefields but will also remove any other settings the user has made, if you want to preserve other settings and just remove the filefield, then ensure the form does not validate somehow so that it renders again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top