Skip to Content
FeaturesModulesFile Cleanup

File Cleanup

The django_cleanup module automatically deletes files from storage when Django model instances with FileField or ImageField are deleted or updated. It works via Django signals, schedules deletions inside transaction.on_commit() for safety, and requires no changes to existing models.

What It Handles

TriggerBehavior
Instance deletedAll file fields on the instance are deleted from storage
File field replacedOld file is deleted when a new value is saved
Soft-deleted instanceFiles are not deleted — soft-delete fields are detected automatically
Model in exclude_modelsSignals not connected — files never touched
Field in exclude_fieldsThat field skipped — others cleaned up normally

Installation

django_cleanup is a built-in module in Django-CFG and is always included in INSTALLED_APPS automatically. No manual setup is needed.

Zero-Config Usage

With default settings, all FileField and ImageField on all models are covered automatically:

class Report(models.Model): pdf = models.FileField(upload_to="reports/") cover = models.ImageField(upload_to="covers/", null=True) # Delete instance → pdf and cover files deleted from storage report.delete() # Replace pdf → old file deleted, new file kept report.pdf = new_file report.save()

Configuration

Cleanup behavior lives in FileCleanupConfig, passed as StorageConfig.cleanup:

from django_cfg import DjangoConfig, StorageConfig, FileCleanupConfig class MyConfig(DjangoConfig): storage = StorageConfig( cleanup=FileCleanupConfig( auto_cleanup=True, delete_on_replace=True, log_deletions=True, exclude_models={"backups.DatabaseBackup"}, exclude_fields={"docs.Contract.original_scan"}, check_shared_files=False, respect_soft_delete=True, soft_delete_fields={"deleted_at", "is_deleted", "deleted"}, ) )

Passing these fields directly to StorageConfig still works but is deprecated and emits a DeprecationWarning. StorageConfig is now a container for cleanup and backend, which are independent.

Disabling the Module

class MyConfig(DjangoConfig): storage = StorageConfig(enabled=False)

Configuration Fields

enabled is on StorageConfig; the rest are on FileCleanupConfig.

FieldTypeDefaultDescription
enabledboolTrueEnable the cleanup module entirely. When False the app is left out of INSTALLED_APPS and no signals are registered
auto_cleanupboolTrueRegister signals for all models with file fields at startup
delete_on_replaceboolTrueDelete old file when a field is updated with a new value
exclude_modelsset[str]set()Models to skip. Format: "app_label.ModelName"
exclude_fieldsset[str]set()Fields to skip. Format: "app_label.ModelName.field_name"
log_deletionsboolFalseLog each deleted file at INFO level
check_shared_filesboolFalseCheck if another record references the same file before deleting
respect_soft_deleteboolTrueSkip file deletion for soft-deleted instances
soft_delete_fieldsset[str]{"deleted_at", "is_deleted", "deleted"}Field names that indicate a soft-delete pattern
outboxboolFalseRecord deletions in a database table and let a worker delete the files with retries. See Delete sync
mode"delete" | "queue_only""delete"queue_only writes the rows and deletes nothing here: another service owns the files
allowed_prefixeslist[str][]Key roots the worker may delete under. Required for prefix deletes
dry_runboolFalseLog what would be deleted, change nothing
max_attemptsint8Attempts before a row is marked failed
backoff_secondsint30First retry delay; grows exponentially with jitter, capped at 6 hours
batch_sizeint200Rows per worker run
schedule_intervalint60Seconds between scheduled runs (needs django_rq)

check_shared_files=True adds one extra DB query per file field at deletion time. Enable only when your data model shares file paths across rows.

Exclusion Formats

FileCleanupConfig( exclude_models={ "backups.DatabaseBackup", # entire model excluded "audit.AuditLog", }, exclude_fields={ "documents.Contract.original_scan", # only this field excluded "users.Profile.legacy_avatar", }, )

Both fields accept lists — they are automatically converted to sets on initialization.

How Signals Work

1. pre_save → cache original file values before save 2. post_save → compare with originals, schedule deletion for replaced files 3. post_delete → schedule deletion for all files on deleted instance All deletions run inside transaction.on_commit() — files survive if the transaction rolls back.

When auto_cleanup=True, the DjangoCleanupConfig.ready() method iterates all registered models, checks for file fields, and connects the three signals using dispatch_uid to prevent duplicate connections.

Soft-Delete Support

If a model has any field whose name appears in soft_delete_fields, the module detects a soft-delete pattern. Files are not deleted when the instance is soft-deleted — only when it is hard-deleted.

class Article(models.Model): cover = models.ImageField(upload_to="articles/") deleted_at = models.DateTimeField(null=True) # Soft delete — file preserved article.deleted_at = timezone.now() article.save() # Hard delete — file deleted article.delete()

Custom soft-delete field names:

FileCleanupConfig( respect_soft_delete=True, soft_delete_fields={"deleted_at", "is_deleted", "removed_at"}, )

Storage Backend Compatibility

Works with any Django storage backend that implements the standard Storage interface:

  • FileSystemStorage (default)
  • S3Boto3Storage from django-storages
  • GoogleCloudStorage from django-storages
  • Azure Blob storage from django-storages
  • Any custom storage backend

To move media onto S3-compatible object storage, see Media Storage — StorageConfig.backend and cleanup are independent settings on the same model.

Per-Model Control with FileCleanupMixin

When auto_cleanup=False, use FileCleanupMixin on models that need explicit cleanup:

from django_cfg.modules.django_cleanup import FileCleanupMixin class Contract(FileCleanupMixin, models.Model): signed_pdf = models.FileField(upload_to="contracts/") draft_pdf = models.FileField(upload_to="drafts/") # Exclude specific fields from cleanup file_cleanup_exclude_fields = ["draft_pdf"]

The mixin overrides delete() and save() to handle cleanup. You can also trigger cleanup manually:

contract.cleanup_file("signed_pdf") # delete one field contract.cleanup_all_files() # delete all fields

Bulk Delete with FileCleanupQuerySet

Regular QuerySet.delete() issues a single SQL DELETE without loading instances — files are never cleaned up. Use FileCleanupQuerySet to fix this:

from django_cfg.modules.django_cleanup import FileCleanupQuerySet class Report(models.Model): file = models.FileField(upload_to="reports/") objects = models.Manager.from_queryset(FileCleanupQuerySet)() # Loads all instances first, then deletes — files are cleaned up Report.objects.filter(archived=True).delete()

FileCleanupQuerySet.delete() fetches all matching instances before deleting. It is more expensive than regular bulk delete but ensures files are cleaned up.

Delete sync

Deleting a row should also remove its files from the bucket and their URLs from the CDN. The default on_commit delete cannot promise that: if the process dies between the commit and the callback, or the storage call fails once, the file stays forever. Delete sync is the opt-in fix: FileCleanupConfig(outbox=True).

The delete handler writes a StorageDeletion row inside the transaction. A rollback discards it, a commit makes it durable. A worker then deletes the files with retries and exponential backoff, never inside a transaction.

StorageConfig( backend=S3StorageConfig.r2(account_id="…", bucket_name="media"), cleanup=FileCleanupConfig( outbox=True, allowed_prefixes=["films/", "avatars/"], # roots the worker may delete under ), cdn=CDNPurgeConfig(base_url="https://cdn.example.com"), # optional )

Declare what an object owns

FileField columns are covered automatically. Files that are not a field (a folder of renditions, a cover derived from the slug) are declared once, in AppConfig.ready():

from django_cfg.modules.django_cleanup import register_owned_files register_owned_files( Film, keys=lambda film: [f"films/{film.pk}/", f"covers/{film.slug}.jpg"], # a trailing "/" is a prefix storage="default", # a STORAGES alias all_keys=lambda: (f"films/{pk}/" for pk in Film.objects.values_list("pk", flat=True)), )

It works for models you cannot edit. all_keys lists every key that is live today; storage_orphans needs it to tell an orphan from a live file.

What the worker does

Scheduled through django_rq when it is on, nudged after each commit, and runnable by hand. For every due row it:

  1. claims the row with a 15 minute lease, so two workers never take the same one;
  2. refuses what the guard dislikes: an empty key, .., a leading /, a prefix outside allowed_prefixes, a prefix equal to an allowed root, any prefix when no list is set;
  3. expands a prefix, deletes each key (a missing object counts as deleted) and logs it;
  4. purges the URLs from Cloudflare in batches. The token and zone come from CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID. A failed purge is retried alone; with no token the purge is skipped and counted;
  5. on an error, backs off and retries; after max_attempts the row is failed.

A row ends as done, failed or refused.

Commands

CommandDoes
manage.py storage_outbox [--json]Row counts and the age of the oldest pending row
manage.py storage_outbox --drain [--dry-run] [--limit N]One worker run by hand
manage.py storage_outbox --retry-failedGive failed rows a fresh set of attempts
manage.py storage_orphans [--json] [--limit N]Files under allowed_prefixes that no registration claims. Report only
manage.py storage_orphans --enqueueWrite the orphans to the outbox; the guard still applies

Not caught: _raw_delete, database-level ON DELETE CASCADE and raw SQL fire no post_delete. Plain QuerySet.delete() and ORM cascades do. storage_orphans finds what the other routes leave behind. Try a new registration on a test bucket first, and set environment on a shared bucket (see Media Storage).

Updating the package adds one table (django_cleanup_storagedeletion). Nothing else changes until you opt in.

Public API

All public symbols are importable from django_cfg.modules.django_cleanup:

from django_cfg.modules.django_cleanup import ( # Config StorageCleanupConfig, get_config, clear_config_cache, # Cleanup functions cleanup_instance_files, delete_file, delete_file_by_name, get_file_fields, is_file_shared, is_model_excluded, has_soft_delete, is_soft_deleted, # Mixins (lazy loaded) FileCleanupMixin, FileCleanupQuerySet, # Signal management connect_signals_for_model, disconnect_signals_for_model, # Delete sync register_owned_files, collect_instance_files, )

Where Configuration Comes From

DjangoConfig.storage.cleanup, falling back to built-in defaults when no config is loaded.

A settings.DJANGO_STORAGE fallback was documented in earlier versions. It was removed in 2.3.0 — django-cfg never wrote that setting, so the path was unreachable. DjangoConfig is the single source of truth.

Troubleshooting

Files Not Being Deleted

  1. Check if model is excluded: is_model_excluded(MyModel, get_config())
  2. Check if soft-delete is active: is_soft_deleted(instance, get_config())
  3. Enable logging: FileCleanupConfig(log_deletions=True)

Rows stay in the outbox

manage.py storage_outbox shows the counts. failed rows carry last_error; fix the cause (credentials, a prefix missing from allowed_prefixes) and run storage_outbox --retry-failed. A refused row broke a guard rule and will not run on its own.

Files Deleted Unexpectedly

  1. Add model to exclusions: exclude_models={"myapp.MyModel"}
  2. Add field to exclusions: exclude_fields={"myapp.MyModel.keep_this"}

TAGS: file-cleanup, storage, filefield, imagefield, signals DEPENDS_ON: [configuration]

Last updated on