Django delete FileField Cleanup Files (and Images) On Model Delete in Django

How to delete file when models instance is delete or update



Django delete FileField Cleanup Files (and Images) On Model Delete in Django.

We are making a small invoicing system to make accounting of different niches easier.

In this application we work a lot with files so see a simple example.


from django.db import models

from Transaction.models import Transaction

from django.utils.translation import gettext as _

from django.utils.text import slugify

from django.dispatch import receiver

import os

import uuid



def directory_path(instance, filename):

    # file will be uploaded to MEDIA_ROOT//<filename>

    year = slugify(instance.transaction.accounting_period.year)

    periode = slugify(instance.transaction.accounting_period.name)

    trader = slugify(instance.transaction.trader)

    return '{0}/{1}/{2}/{3}'.format(year, periode, trader,  filename)


class Document(models.Model):

    transaction = models.ForeignKey('Transaction.Transaction', related_name='transaction', on_delete=models.CASCADE)

    invoice = models.FileField(upload_to=directory_path)

    def __unicode__(self):

        return u"%s" % (self.id)



@receiver(models.signals.pre_save, sender=Document)

def auto_delete_file_on_change(sender, instance, **kwargs):

    """

    Replace Document 

    """

    if not instance.pk:

        return False


    try:

        old_file = Document.objects.get(pk=instance.pk).invoice

    except Document.DoesNotExist:

        return False


    new_file = instance.invoice

    if not old_file == new_file:

        if os.path.isfile(old_file.path):

            os.remove(old_file.path)



@receiver(models.signals.post_delete, sender=Document)

def auto_delete_file_on_delete(sender, instance, **kwargs):

    """

    Delete Document

    """

    if instance.invoice:

        if os.path.isfile(instance.invoice.path):

            os.remove(instance.invoice.path)




Comments