📜  django cleanup - Python (1)

📅  最后修改于: 2023-12-03 15:00:26.278000             🧑  作者: Mango

Django Cleanup - Python

Django Cleanup is a package for managing Media files within a Django project. It is designed to cleanup Orphaned and unnecessary files that are no longer required by the project, freeing up space on the server.

Installation

You can install 'django-cleanup' using pip:

pip install django-cleanup

Once installed, add 'django_cleanup' to INSTALLED_APPS in 'settings.py' file:

INSTALLED_APPS = [
    # ...
    'django_cleanup',
    # ...
]
How it works?

Django Cleanup automatically deletes files when the model instance is deleted from the database. It can also look for model instances which are no longer used and any file attached to these unused instances are automatically deleted.

Django Cleanup uses signal processing to monitor the deletion of the model instances, and then marks the corresponding file for deletion.

Usage

Django Cleanup provides a model field called CleanupImageField that you can use in place of Django's ImageField:

from django_cleanup import cleanup

class MyModel(models.Model):
    image = CleanupImageField(upload_to='myfolder')

You can also use the django_cleanup.cleanup() function as a decorator on your view functions to automatically delete all the orphaned files in a directory:

from django_cleanup import cleanup

@cleanup.ignore
def my_view(request):
   pass
Configuration

Django Cleanup can be configured using the following options in your settings.py file:

CLEANUP_IGNORE_EXTENSIONS = ['.pdf', '.doc', '.xls']

This option will tell Django Cleanup to ignore files with a certain extension.

CLEANUP_KEEP_PARENT_DIR = True

This option will tell Django Cleanup to keep the parent directory of the file even if it is empty.

Conclusion

Django Cleanup is a very useful package that can help you manage your media files with ease. It automatically cleans up unused files, freeing up disk space on your server. We hope this article has helped you understand more about Django Cleanup and how to use it in your projects.