Blog Entry 4 years, 11 months ago

Some Notes about Django

Some small hints/notes about deleting media files, referenced object, and sorl-thumbnail

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 raising ProtectedError, a subclass of django.db.IntegrityError.
  • SET_NULL: Set the ForeignKey null; this is only possible if null is True.
  • SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.
  • SET(): Set the ForeignKey to 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 IntegrityError unless 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)
Recent Reads