Delete uploaded files (in media directory)
As default, Django keeps uploaded files inside media directory when the object containing FileField or ImageField is deleted. That could lead to insufficient storage issue after running web application for a long (or short) time.
In order to completely delete those files, we should implement a function or method doing that then registering as a receiver of signal pre_delete (or post_delete)of target model.
from django.db.models.signals import pre_delete from django.dispath import receiver ... @receiver(pre_delete, sender=TheModel) def delete_mediafiles(sender, instance, **kwargs): if instance.file: instance.file.delete(False)
Change behavior with referenced object in case of deletion
This part is mostly mentioning about on_delete argument of ForeignKey field declaration. Default value of this is CASCADE, it means related object will be deleted at object's deletion. Following Django documentation, you could change this to one of other values to better match your need:
PROTECT: Prevent deletion of the referenced object by raisingProtectedError, a subclass ofdjango.db.IntegrityError.SET_NULL: Set theForeignKeynull; this is only possible if null isTrue.SET_DEFAULT: Set theForeignKeyto its default value; a default for theForeignKeymust be set.SET(): Set theForeignKeyto the value passed toSET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:DO_NOTHING: Take no action. If your database backend enforces referential integrity, this will cause anIntegrityErrorunless you manually add an SQL ON DELETE constraint to the database field (perhaps using initial sql).
Last one, a bit about sorl-thumbnail
If you want to resize/process the image in code instead of inside template or model, just use function get_thumbnail(), with same parameters:
from sorl.thumbnail import get_thumbnail thumb = get_thumbnail(image, '120x120', upscale=False, quality=99)