23 lines
768 B
Python
23 lines
768 B
Python
import os
|
|
from django.conf import settings
|
|
from django.db.models.signals import post_delete
|
|
from django.dispatch import receiver
|
|
|
|
from .models import PostImages
|
|
|
|
|
|
@receiver(post_delete, sender=PostImages)
|
|
def delete_image_file(sender, instance, **kwargs):
|
|
"""
|
|
Deletes the associated image file from the filesystem when a PostImages instance is deleted.
|
|
"""
|
|
# Check if the instance has a path and the path is not empty
|
|
if instance.path:
|
|
file_path = os.path.join(settings.MEDIA_ROOT, instance.path)
|
|
if os.path.exists(file_path):
|
|
try:
|
|
os.remove(file_path)
|
|
except OSError as e:
|
|
# Optionally, log the error e.g., print(f"Error deleting file {file_path}: {e}")
|
|
pass
|