Search code examples
djangodjango-formsfilefielddjango-uploads

How to deselct something when selected previously in FileField Django Form?


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


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+'\')" />');
        });   
    });