import django.newforms as forms from django.db import models import os class DeleteCheckboxWidget(forms.CheckboxInput): def __init__(self, *args, **kwargs): self.show_delete = kwargs.pop('show_delete') super(DeleteCheckboxWidget, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None): if self.show_delete: return u'' % (attrs['id'], super(DeleteCheckboxWidget, self).render(name, value, attrs), _('Delete')) else: return u'' class RemovableFileFormWidget(forms.MultiWidget): def __init__(self, show_delete=False): widgets = (forms.FileInput(), DeleteCheckboxWidget(show_delete=show_delete)) super(RemovableFileFormWidget, self).__init__(widgets) def decompress(self, value): return [None, None] class RemovableFileFormField(forms.MultiValueField): widget = RemovableFileFormWidget field = forms.FileField def __init__(self, *args, **kwargs): fields = [self.field(*args, **kwargs), forms.BooleanField(required=False)] if kwargs.get('initial'): self.widget = self.widget(show_delete=True) super(RemovableFileFormField, self).__init__(fields, required=False) def compress(self, data_list): return data_list class RemovableImageFormField(RemovableFileFormField): field = forms.ImageField class RemovableFileField(models.FileField): def delete_file(self, instance): if getattr(instance, self.attname): file_name = getattr(instance, 'get_%s_filename' % self.name)() # If the file exists and no other object of this type references it, # delete it from the filesystem. if os.path.exists(file_name) and \ not instance.__class__._default_manager.filter(**{'%s__exact' % self.name: getattr(instance, self.attname)}).exclude(pk=instance._get_pk_val()): os.remove(file_name) def get_internal_type(self): return 'FileField' def save_form_data(self, instance, data): if data: if not data[1]: self.delete_file(instance) super(RemovableFileField, self).save_form_data(instance, data[0]) else: self.delete_file(instance) setattr(instance, self.name, None) def formfield(self, **kwargs): defaults = {'form_class': RemovableFileFormField} defaults.update(kwargs) return super(RemovableFileField, self).formfield(**defaults) class RemovableImageField(models.ImageField, RemovableFileField): def formfield(self, **kwargs): defaults = {'form_class': RemovableImageFormField} defaults.update(kwargs) return super(RemovableFileField, self).formfield(**defaults)