55👍
Try django-cleanup, it automatically invokes delete method on FileField when you remove model.
pip install django-cleanup
settings.py
INSTALLED_APPS = (
...
'django_cleanup.apps.CleanupConfig', # should go after your apps
)
16👍
django-unused-media will help you to clean old unused media by management command.
Very useful when you just started to use django-cleanup
and already have files which needs to be deleted.
Or if you have thumbnails which needs to be deleted from media directory.
- [Django]-How to create virtual env with python3
- [Django]-Do properties work on Django model fields?
- [Django]-How to customize user profile when using django-allauth
4👍
Perhaps this is a bit late, but if you also want to know more about the problems that can appear with deletion, here’s an article which explains how to delete them in two ways (with code snippets).
There is a management command which can be called every now and then, and a more “immediate” solution, using signals.
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
- [Django]-DatabaseError: value too long for type character varying(100)
- [Django]-Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
2👍
You can use signals. Than use os.remove() to clean up related files on delete.
This way your file system always reflects you db. No need for hitting some button.
- [Django]-How do I perform query filtering in django templates
- [Django]-Create Custom Error Messages with Model Forms
- [Django]-Should I be adding the Django migration files in the .gitignore file?
1👍
The following is how I currently do it with Django 1.7 which need to be used from the start I don’t know how you clean up unreferenced files in retrospect.
Say you’ve got an app named ‘cars’ and a model named ‘Car’.
signals.py:
# cars/signals.py
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_delete
from cars.models import Car
# By adding 'Car' as 'sender' argument we only receive signals from that model
@receiver(post_delete, sender=Car)
def on_delete(sender, **kwargs):
instance = kwargs['instance']
# ref is the name of the field file of the Car model
# replace with name of your file field
instance.ref.delete(save=False)
apps.py:
# cars/apps.py
from django.apps import AppConfig
class CarConfig(AppConfig):
name = "cars"
def ready(self):
import cars.signals
__init__.py:
default_app_config = 'cars.apps.CarConfig'
- [Django]-Django contrib admin default admin and password
- [Django]-Django py.test does not find settings module
- [Django]-Include intermediary (through model) in responses in Django Rest Framework