Login

Removing old ImageFields and FileFields when updating through admin

Author:
alejandro.alonso
Posted:
May 4, 2012
Language:
Python
Version:
1.4
Tags:
newforms models imagefield filefield remove delete
Score:
1 (after 1 ratings)

Example:

admin.site.register(YourCoolModel, CustomModelAdmin)

 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
from django.contrib.admin.util import unquote
from django.db import models as django_models
import os 

class CustomModelAdmin(admin.ModelAdmin):
    def change_view(self, request, object_id, extra_context=None):
        #Original ImageField attr's
        obj = self.get_object(request, unquote(object_id))
        for field in obj._meta.fields:
            if (isinstance(field, django_models.ImageField) or isinstance(field, django_models.FileField))\
                    and request.FILES.has_key(field.name):
                setattr(obj, 'old_%s'%(field.name), getattr(obj, field.name)) 
                
        ModelForm = self.get_form(request, obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                for field in obj._meta.fields:
                    #Overwriting ImageField attr's
                    if (isinstance(field, django_models.ImageField) or isinstance(field, django_models.FileField))\
                            and request.FILES.has_key(field.name):
                        path = getattr(obj, 'old_%s'%(field.name))
                        if path and os.path.isfile(path.path):
                            os.unlink(path.path)

        return super(CustomModelAdmin, self).change_view(request, object_id, extra_context=extra_context)

More like this

  1. Add a "remove file" field for Image- or FileFields by rodrigoc 6 years, 8 months ago
  2. FileField / ImageField with a delete checkbox by tomZ 7 years, 4 months ago
  3. Updated FileField / ImageField with a delete checkbox by tomZ 7 years ago
  4. REMOVE IMAGEFIELD ATTACHMENT IN DJANGO by timonweb 2 years, 10 months ago
  5. Amazon S3 Enabled FileField and ImageField (with Boto) by natebeacham 4 years, 11 months ago

Comments

benkonrath (on May 16, 2012):

Thanks for this snippet.

I had to check if obj has the _meta attribute to avoid a server error when I click on a link to a item that has been deleted from the recent changes side-box. Putting if hasattr(obj, '_meta'): before the first for field in obj._meta.fields: loop (line 9) and updating the indentation accordingly fixes this problem. Thanks again!

#

Please login first before commenting.