Automatically deletes old file for FileField and ImageField. It also deletes files on models instance deletion.

Overview

Django Cleanup

PyPI Package Build Status MIT License

Features

The django-cleanup app automatically deletes files for FileField, ImageField and subclasses. When a FileField's value is changed and the model is saved, the old file is deleted. When a model that has a FileField is deleted, the file is also deleted. A file that is set as the FileField's default value will not be deleted.

Compatibility

How does it work?

In order to track changes of a FileField and facilitate file deletions, django-cleanup connects post_init, pre_save, post_save and post_delete signals to signal handlers for each INSTALLED_APPS model that has a FileField. In order to tell whether or not a FileField's value has changed a local cache of original values is kept on the model instance. If a condition is detected that should result in a file deletion, a function to delete the file is setup and inserted into the commit phase of the current transaction.

Warning! If you are using a database that does not support transactions you may lose files if a transaction will rollback at the right instance. This outcome is mitigated by our use of post_save and post_delete signals, and by following the recommended configuration below. This outcome will still occur if there are signals registered after app initialization and there are exceptions when those signals are handled. In this case, the old file will be lost and the new file will not be referenced in a model, though the new file will likely still exist on disk. If you are concerned about this behavior you will need another solution for old file deletion in your project.

Installation

pip install django-cleanup

Configuration

Add django_cleanup to the bottom of INSTALLED_APPS in settings.py

INSTALLED_APPS = (
    ...,
    'django_cleanup.apps.CleanupConfig',
)

That is all, no other configuration is necessary.

Note: Order of INSTALLED_APPS is important. To ensure that exceptions inside other apps' signal handlers do not affect the integrity of file deletions within transactions, django_cleanup should be placed last in INSTALLED_APPS.

Troubleshooting

If you notice that django-cleanup is not removing files when expected, check that your models are being properly loaded:

You must define or import all models in your application's models.py or models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.

If your models are not loaded, django-cleanup will not be able to discover their FileField's.

You can check if your Model is loaded by using

from django.apps import apps
apps.get_models()

Advanced

This section contains additional functionality that can be used to interact with django-cleanup for special cases.

Signals

To facilitate interactions with other django apps django-cleanup sends the following signals which can be imported from django_cleanup.signals:

  • cleanup_pre_delete: just before a file is deleted. Passes a file keyword argument.
  • cleanup_post_delete: just after a file is deleted. Passes a file keyword argument.

Signals example for sorl.thumbnail:

from django_cleanup.signals import cleanup_pre_delete
from sorl.thumbnail import delete

def sorl_delete(**kwargs):
    delete(kwargs['file'])

cleanup_pre_delete.connect(sorl_delete)

Refresh the cache

There have been rare cases where the cache would need to be refreshed. To do so the django_cleanup.cleanup.refresh method can be used:

from django_cleanup import cleanup

cleanup.refresh(model_instance)

Ignore cleanup for a specific model

Ignore a model and do not perform cleanup when the model is deleted or its files change.

from django_cleanup import cleanup

@cleanup.ignore
class MyModel(models.Model):
    image = models.FileField()

How to run tests

Install, setup and use pyenv to install all the required versions of cPython (see the tox.ini).

Setup pyenv to have all versions of python activated within your local django-cleanup repository. Ensuring that the python 3.8 that was installed is first priority.

Install tox on python 3.8 and run the tox command from your local django-cleanup repository.

How to write tests

This app requires the use of django.test.TransactionTestCase when writing tests.

For details on why this is required see here:

Django's TestCase class wraps each test in a transaction and rolls back that transaction after each test, in order to provide test isolation. This means that no transaction is ever actually committed, thus your on_commit() callbacks will never be run. If you need to test the results of an on_commit() callback, use a TransactionTestCase instead.

License

django-cleanup is free software under terms of the:

MIT License

Copyright (C) 2012 by Ilya Shalyapin, [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Django-cleanup seems not working anymore on Django 1.8

    Django-cleanup seems not working anymore on Django 1.8

    Django 1.8.5 Django-cleanup 0.4.0

    File "/home/khamaileon/workspace/khamaileon/project/api/feed/models.py", line 73, in fetch
        self.save()
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django/db/models/base.py", line 734, in save
        force_update=force_update, update_fields=update_fields)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django/db/models/base.py", line 771, in save_base
        update_fields=update_fields, raw=raw, using=using)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django/dispatch/dispatcher.py", line 201, in send
        response = receiver(signal=self, sender=sender, **named)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django_cleanup/models.py", line 65, in delete_old_post_save
        delete_file(old_file, using)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django_cleanup/models.py", line 87, in delete_file
        on_commit(run_on_commit, using)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django_cleanup/models.py", line 17, in on_commit
        func()
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django_cleanup/models.py", line 84, in run_on_commit
        file_.delete(save=False)
      File "/home/khamaileon/.virtualenvs/project-api/lib/python3.4/site-packages/django/db/models/fields/files.py", line 124, in delete
        self.storage.delete(self.name)
    AttributeError: 'FieldFile' object has no attribute 'storage'
    
    opened by khamaileon 24
  • Cleanup cached thumbnails

    Cleanup cached thumbnails

    Not sure if this should be in scope, but what would be the best approach to order generated thumbnails? I am using https://github.com/SmileyChris/easy-thumbnails

    Thanks for a nice library!

    opened by philippeluickx 18
  • cleanup command

    cleanup command

    It would be very nice to have a command that iterate over all file fields an delete all media-files (under a path specified by a setting) that are not used by any model-field anymore. This would be very useful for existing projects where django-cleanup was not installed since the beginning.

    enhancement 
    opened by fabiocaccamo 14
  • Does this package support djangorestframework (drf)?

    Does this package support djangorestframework (drf)?

    I am using DRF to provide a REST API on top of Django. I recently noticed that Django does not automatically delete files on disk when the FileField is deleted, so I was hoping django-cleanup could address this.

    setup.py:

    INSTALLED_APPS = [
        'grappelli',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'myapp.apps.MyAppConfig',
        'debug_toolbar',
        'guardian',
        'django_cleanup.apps.CleanupConfig',
    ]
    

    models.py:

    class Project(models.Model):
        pass
    
    class MyModel(models.Model):
        project = models.ForeignKey(Project, related_name='my_models', on_delete=models.CASCADE)
        image = models.ImageField(upload_to='my_images')
    

    But when I do a RESTful DELETE of an instance of Project, the files still don't delete?

    The DRF ModelSerializer for Project deletes all of the Project and MyModel instances correctly (the database is empty), but the files remain.

    Is there any configuration needed in MyAppConfig to associate the model? Is there a way to debug why django-cleanup doesn't seem to be getting called?

    Wanted to check that this wasn't some kind of known limitation.

    opened by johnthagen 12
  • save() raises FileNotFoundError

    save() raises FileNotFoundError

    Hello, Ilya!

    We are using this lib in a while. In most cases it works perfect! Saves lots of space..

    Resently my colleague found small issue with manual file removal.. If somewhere in code I already delete a file (or it is disappeared after django created an object) then .save() will raise FileNotFoundError

    >>> obj = MyModel.object.all().first()
    >>> obj.data.delete()
    >>> obj.data = None
    >>> obj.save()  # raises FileNotFoundError
    

    May be it will be better to catch this exception inside this application? In case of, for example, using another library, which is know nothing about django_cleanup?

    I'm ready to create pull request if you don't mind

    enhancement 
    opened by mnacharov 12
  • Deletes Files shared between instances

    Deletes Files shared between instances

    I've discovered that if two models instances share a single file, and one of the instances is deleted, the file is also deleted. Obviously this creates an issue when trying to parse the model as the reference to the file remains, while the file does not.

    opened by Ri-Dearg 8
  • Documentation needs improvement.

    Documentation needs improvement.

    Hello Ilya!

    For example if I have a model that look like this:

    class Profile(models.Model):
        name = models.CharField(max_length=40)
        doc = models.FieldField(upload_to='folder')
    

    The documentation doesn't say how one should use the signals an not every projects need sorl-thumbnail

    opened by styvane 8
  • Deletes unwanted files

    Deletes unwanted files

    I have a model having ImageField (default to some image). When the ImageField is updated by any instance of the model, the default image is deleted. This causes problems when many instances of same model are linked with default image, and one of them updates.

    Reference: my project Develop branch, Profile model.

    opened by harshraj22 7
  • Infinite recursion between django-modeltranslations and django-cleanup

    Infinite recursion between django-modeltranslations and django-cleanup

    Not sure if it's related to a recent upgrade to django 1.10 but there is an infinite recursion between django-cleanup and django modeltranslations.

    django-cleanup==0.4.2 django-modeltranslation==0.12 Django==1.10

    File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/base.py", line 557, in init signals.post_init.send(sender=self.class, instance=self) File "/site/env/python/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "/site/env/python/local/lib/python2.7/site-packages/django_cleanup/handlers.py", line 44, in cache_original_post_init cache.make_cleanup_cache(instance) File "/site/env/python/local/lib/python2.7/site-packages/django_cleanup/cache.py", line 165, in make_cleanup_cache fields_for_model_instance(source, using=instance))) File "/site/env/python/local/lib/python2.7/site-packages/django_cleanup/cache.py", line 108, in fields_for_model_instance field = get_field_instance(instance, field_name, using=using) File "/site/env/python/local/lib/python2.7/site-packages/django_cleanup/cache.py", line 82, in get_field_instance field = getattr(instance, field_name, None) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/fields/files.py", line 173, in get instance.refresh_from_db(fields=[self.field.name]) File "/site/env/python/local/lib/python2.7/site-packages/modeltranslation/translator.py", line 304, in new_refresh_from_db return old_refresh_from_db(self, using, fields) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/base.py", line 685, in refresh_from_db db_instance = db_instance_qs.get() File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/query.py", line 379, in get num = len(clone) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/query.py", line 238, in len self._fetch_all() File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/query.py", line 1085, in _fetch_all self._result_cache = list(self.iterator()) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/query.py", line 66, in iter obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/base.py", line 565, in from_db new = cls(*values) File "/site/env/python/local/lib/python2.7/site-packages/modeltranslation/translator.py", line 245, in new_init old_init(self, *args, **kwargs) File "/site/env/python/local/lib/python2.7/site-packages/django/db/models/base.py", line 557, in init signals.post_init.send(sender=self.class, instance=self)

    bug 
    opened by Paul424 7
  • Совместимость с django 1.7

    Совместимость с django 1.7

    Здравствуйте! Успешно использую Ваше приложение. Но при обновлении до django-1.7b2 приложение выдает ошибку.

    raise RuntimeError("App registry isn't ready yet.") RuntimeError: App registry isn't ready yet.

    opened by v-bornov 7
  • Data loss if same file is saved in multiple fields

    Data loss if same file is saved in multiple fields

    If a file is saved in multiple instances, then removing a single instance removes the file and cause 'file not found' error for every other instance.

    We need to check if the file is referenced in any other object before deleting.

    opened by singhravi1 6
  • FileField ID in pre-delete

    FileField ID in pre-delete

    To delete a file in a non-typical storage location, I required the file ID. The problem is that cleanup_pre_delete() was being called AFTER the FakeInstance(), which effectively wipes the id from the instance. My solution is to move cleanup_pre_delete() before calling FakeInstance(). Not sure what other impact this has...

    opened by NadavK 0
  • Feature/7.0

    Feature/7.0

    Add django 4.1. Add Python 3.11. Add select mode option, models would be explicitly selected using the @cleanup.select decorator. Resolves #75.

    Remove django 2.2 and python 3.5.

    opened by vinnyrose 0
  • Have option to use django-cleanup explicitly on models

    Have option to use django-cleanup explicitly on models

    By default, django-cleanup works by cleaning all models unless you explicitly ignore them with @cleanup.ignore. I'm wondering if django-cleanup could work in such a way that it doesn't cleanup any models unless you explicitly ask it to?

    For example:

    @cleanup.cleanup
    class UserImage(models.Model):
        image = models.FileField()
    
    enhancement 
    opened by daviddavis 5
Owner
Ilya Shalyapin
Ilya Shalyapin
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files.

Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards in settings file paths and mark setti

Nikita Sobolev 940 Jan 3, 2023
Stream Framework is a Python library, which allows you to build news feed, activity streams and notification systems using Cassandra and/or Redis. The authors of Stream-Framework also provide a cloud service for feed technology:

Stream Framework Activity Streams & Newsfeeds Stream Framework is a Python library which allows you to build activity streams & newsfeeds using Cassan

Thierry Schellenbach 4.7k Jan 2, 2023
django Filer is a file management application for django that makes handling of files and images a breeze.

django Filer is a file management application for django that makes handling of files and images a breeze.

django CMS Association 1.6k Jan 6, 2023
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 8, 2021
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Jan 7, 2023
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Dec 31, 2022
Updates redisearch instance with igdb data used for kimosabe

igdb-pdt Update RediSearch with IGDB games data in the following Format: { "game_slug": { "name": "game_name", "cover": "igdb_coverart_url",

6rotoms 0 Jul 30, 2021
A tool to automatically fix Django deprecations.

A tool to help upgrade Django projects to newer version of the framework by automatically fixing deprecations. The problem When maintaining a Django s

Bruno Alla 155 Dec 14, 2022
Duckiter will Automatically dockerize your Django projects.

Duckiter Duckiter will Automatically dockerize your Django projects. Requirements : - python version : python version 3.6 or upper version - OS :

soroush safari 23 Sep 16, 2021
Automatically reload your browser in development.

django-browser-reload Automatically reload your browser in development. Requirements Python 3.6 to 3.10 supported. Django 2.2 to 4.0 supported. Are yo

Adam Johnson 254 Jan 4, 2023
Compresses linked and inline javascript or CSS into a single cached file.

Django Compressor Django Compressor processes, combines and minifies linked and inline Javascript or CSS in a Django template into cacheable static fi

null 2.6k Jan 3, 2023
File and Image Management Application for django

Django Filer django Filer is a file management application for django that makes handling of files and images a breeze. Contributing This is a an open

django CMS Association 1.6k Dec 28, 2022
Management commands to help backup and restore your project database and media files

Django Database Backup This Django application provides management commands to help backup and restore your project database and media files with vari

null 687 Jan 4, 2023
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Dec 15, 2022
Cached file system for online resources in Python

Minato Cache & file system for online resources in Python Features Minato enables you to: Download & cache online recsources minato supports the follo

Yasuhiro Yamaguchi 10 Jan 4, 2023
A Django app for managing robots.txt files following the robots exclusion protocol

Django Robots This is a basic Django application to manage robots.txt files following the robots exclusion protocol, complementing the Django Sitemap

Jazzband 406 Dec 26, 2022
Serve files with Django.

django-downloadview django-downloadview makes it easy to serve files with Django: you manage files with Django (permissions, filters, generation, ...)

Jazzband 328 Dec 7, 2022
Packs a bunch of smaller CSS files together from 1 folder.

Packs a bunch of smaller CSS files together from 1 folder.

null 1 Dec 9, 2021