- Author:
- alejandro.alonso
- Posted:
- May 4, 2012
- Language:
- Python
- Version:
- 1.4
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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. Puttingif hasattr(obj, '_meta'):
before the firstfor field in obj._meta.fields:
loop (line 9) and updating the indentation accordingly fixes this problem. Thanks again!#
Please login first before commenting.