[Django]-Django ClearableFileInput – how to detect whether to delete the file

7👍

You shouldn’t check the checkbox, but check the value of the file input field. If it is False, then you can delete the file. Otherwise it is the uploaded file. See: https://github.com/django/django/blob/339c01fb7552feb8df125ef7e5420dae04fd913f/django/forms/widgets.py#L434

    # False signals to clear any existing value, as opposed to just None
    return False
return upload
👤Serkan

0👍

Let me add here my code that solved the problem – I decided to put this logic to ModelForm.clean():

class Document(models.Model):
    upload = models.FileField(upload_to=document_name, blank=True)

class DocumentForm(ModelForm):
    def clean(self):
        cleaned_data = super(DocumentForm, self).clean()
        upload = cleaned_data['upload']
        if (upload == False) and self.instance.upload:
            if os.path.isfile(self.instance.upload.path):
                self.instance.upload.delete(False)

Leave a comment