Login

FileField / ImageField with a delete checkbox

Author:
tomZ
Posted:
November 17, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Example model:

class MyModel(models.Model):
    file = RemovableFileField(upload_to='files', \
        null=True, blank=True)
    image = RemovableImageField(upload_to='images', \
        null=True, blank=True)

A delete checkbox will be automatically rendered when editing such a model using form_for_instance.

UPDATED version which works with ModelForms

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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'<label for="%s">%s %s</label>' % (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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.