75 řádky
2.1 KiB
Python
75 řádky
2.1 KiB
Python
from django.db.models.signals import pre_delete, pre_save
|
|
from django.dispatch import receiver
|
|
from .models import BottomBar, Setting
|
|
import os
|
|
|
|
|
|
@receiver(pre_delete, sender=BottomBar)
|
|
def bottombar_auto_delete_file_on_delete(instance: BottomBar, **kwargs):
|
|
"""
|
|
Deletes file from filesystem
|
|
when corresponding `BottomBar` object is deleted.
|
|
"""
|
|
if instance.icon:
|
|
if os.path.isfile(instance.icon.path):
|
|
os.remove(instance.icon.path)
|
|
|
|
|
|
@receiver(pre_save, sender=BottomBar)
|
|
def bottombar_auto_delete_file_on_change(instance: BottomBar, **kwargs):
|
|
"""
|
|
Deletes old file from filesystem
|
|
when corresponding `icon` object is updated
|
|
with new file.
|
|
"""
|
|
if not instance.pk:
|
|
return False
|
|
|
|
try:
|
|
old_file = BottomBar.objects.get(pk=instance.pk).icon
|
|
except BottomBar.DoesNotExist:
|
|
return False
|
|
|
|
new_file = instance.icon
|
|
if not old_file == new_file and old_file:
|
|
if os.path.isfile(old_file.path):
|
|
os.remove(old_file.path)
|
|
|
|
|
|
@receiver(pre_delete, sender=Setting)
|
|
def setting_auto_delete_file_on_delete(instance: Setting, **kwargs):
|
|
"""
|
|
Deletes file from filesystem
|
|
when corresponding `Settings` object is deleted.
|
|
"""
|
|
if instance.page_image.path.endswith(instance.page_image.field.default):
|
|
return False
|
|
|
|
if instance.page_image:
|
|
if os.path.isfile(instance.page_image.path):
|
|
os.remove(instance.page_image.path)
|
|
|
|
|
|
@receiver(pre_save, sender=Setting)
|
|
def setting_auto_delete_file_on_change(instance: Setting, **kwargs):
|
|
"""
|
|
Deletes old file from filesystem
|
|
when corresponding `page_image` object is updated
|
|
with new file.
|
|
"""
|
|
if not instance.pk:
|
|
return False
|
|
|
|
try:
|
|
old_file = Setting.objects.get(pk=instance.pk).page_image
|
|
except Setting.DoesNotExist:
|
|
return False
|
|
|
|
if old_file.path.endswith(instance.page_image.field.default):
|
|
return False
|
|
|
|
new_file = instance.page_image
|
|
if not old_file == new_file:
|
|
if os.path.isfile(old_file.path):
|
|
os.remove(old_file.path)
|