Delete uploaded files (in media directory)
As default, Django keeps uploaded files inside media directory when the object containing
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
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 raising
ProtectedError, a subclass of
SET_NULL: Set the
ForeignKeynull; this is only possible if null is
SET_DEFAULT: Set the
ForeignKeyto its default value; a default for the
ForeignKeymust be set.
SET(): Set the
ForeignKeyto the value passed to
SET(), 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 an
IntegrityErrorunless 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)