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
| Trigger | Behavior |
|---|---|
| Instance deleted | All file fields on the instance are deleted from storage |
| File field replaced | Old file is deleted when a new value is saved |
| Soft-deleted instance | Files are not deleted — soft-delete fields are detected automatically |
Model in exclude_models | Signals not connected — files never touched |
Field in exclude_fields | That 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.
| Field | Type | Default | Description |
|---|---|---|---|
enabled | bool | True | Enable the cleanup module entirely. When False the app is left out of INSTALLED_APPS and no signals are registered |
auto_cleanup | bool | True | Register signals for all models with file fields at startup |
delete_on_replace | bool | True | Delete old file when a field is updated with a new value |
exclude_models | set[str] | set() | Models to skip. Format: "app_label.ModelName" |
exclude_fields | set[str] | set() | Fields to skip. Format: "app_label.ModelName.field_name" |
log_deletions | bool | False | Log each deleted file at INFO level |
check_shared_files | bool | False | Check if another record references the same file before deleting |
respect_soft_delete | bool | True | Skip file deletion for soft-deleted instances |
soft_delete_fields | set[str] | {"deleted_at", "is_deleted", "deleted"} | Field names that indicate a soft-delete pattern |
outbox | bool | False | Record 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_prefixes | list[str] | [] | Key roots the worker may delete under. Required for prefix deletes |
dry_run | bool | False | Log what would be deleted, change nothing |
max_attempts | int | 8 | Attempts before a row is marked failed |
backoff_seconds | int | 30 | First retry delay; grows exponentially with jitter, capped at 6 hours |
batch_size | int | 200 | Rows per worker run |
schedule_interval | int | 60 | Seconds 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)S3Boto3Storagefromdjango-storagesGoogleCloudStoragefromdjango-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 fieldsBulk 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:
- claims the row with a 15 minute lease, so two workers never take the same one;
- refuses what the guard dislikes: an empty key,
.., a leading/, a prefix outsideallowed_prefixes, a prefix equal to an allowed root, any prefix when no list is set; - expands a prefix, deletes each key (a missing object counts as deleted) and logs it;
- purges the URLs from Cloudflare in batches. The token and zone come from
CLOUDFLARE_API_TOKENandCLOUDFLARE_ZONE_ID. A failed purge is retried alone; with no token the purge is skipped and counted; - on an error, backs off and retries; after
max_attemptsthe row isfailed.
A row ends as done, failed or refused.
Commands
| Command | Does |
|---|---|
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-failed | Give 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 --enqueue | Write 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
- Check if model is excluded:
is_model_excluded(MyModel, get_config()) - Check if soft-delete is active:
is_soft_deleted(instance, get_config()) - 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
- Add model to exclusions:
exclude_models={"myapp.MyModel"} - Add field to exclusions:
exclude_fields={"myapp.MyModel.keep_this"}
TAGS: file-cleanup, storage, filefield, imagefield, signals DEPENDS_ON: [configuration]