# 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)
Comments
How would I change this to work with regular forms?
#
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
#