Clear FileField/ImageField files in the Admin

 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. Removing old ImageFields and FileFields when updating through admin by alejandro.alonso 1 year, 11 months ago
  2. load m2m fields objects by dirol 3 years, 10 months ago
  3. Temporary admin messages (MOTD) by bthomas 5 years, 2 months ago
  4. REMOVE IMAGEFIELD ATTACHMENT IN DJANGO by timonweb 1 year, 11 months ago
  5. Add a "remove file" field for Image- or FileFields by rodrigoc 5 years, 9 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

#

(Forgotten your password?)