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