Login

Clear FileField/ImageField files in the Admin

Author:
marinho
Posted:
July 15, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

The widget for FileField and ImageField has a problem: it doesn't supports clear its value and it doesn't delete the old file when you replace it for a new one.

This is a solution for this. It is just for Admin, but you can make changes to be compatible with common forms.

The jQuery code will put an <input type="checkbox"> tag next to every <input type="file"> and user can check it to clear the field value.

When a user just replace the current file for a new one, the old file will be deleted.

 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
# Template - you can put this code on admin/base.html or on
# admin/change_form.html, as you want

<script src="{{ MEDIA_URL }}js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('input[type=file]').each(function() {
        $(this).after(' <input type="checkbox" name="clear_image_'+$(this).attr('name')+'"/> Clear');
    });
});
</script>

# Your ModelAdmin

from django.contrib.admin.options import ModelAdmin

class MyModelAdmin(ModelAdmin):
    def save_form(self, request, form, change):
        """Deletes the file from fields FileField/ImageField if
        their values have changed"""

        obj = form.instance
        if obj:
            for field in obj._meta.fields:
                if not isinstance(field, FileField):
                    continue
               
                path = getattr(obj, field.name, None)
                if path and os.path.isfile(path.path):
                    if field.name in form.changed_data or form.data.get('clear_image_'+field.name, ''):
                        os.unlink(path.path)
                        setattr(obj, field.name, None)
           
        return super(MyModelAdmin, self).save_form(request, form, change)

More like this

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

Comments

mpstevens_uk (on July 16, 2009):

How would I change this to work with regular forms?

#

varma.nikhil22 (on March 4, 2012):

This snippet works great for me.I was using Django1.2.5 and its a kind of facility provided in Django1.4b. I wanted this to work in admin and it worked perfectly.

Thanks marinho . Great

#

un1t (on March 17, 2015):

Try django-cleanup

pip install django-cleanup

settings.py

INSTALLED_APPS = (
    ...
    'django_cleanup', # should go after your apps
)

#

Please login first before commenting.