Django Library Themes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from django.db.models.signals import pre_delete, pre_save
  2. from django.dispatch import receiver
  3. from .models import BottomBar, Setting
  4. import os
  5. @receiver(pre_delete, sender=BottomBar)
  6. def bottombar_auto_delete_file_on_delete(instance: BottomBar, **kwargs):
  7. """
  8. Deletes file from filesystem
  9. when corresponding `BottomBar` object is deleted.
  10. """
  11. if instance.icon:
  12. if os.path.isfile(instance.icon.path):
  13. os.remove(instance.icon.path)
  14. @receiver(pre_save, sender=BottomBar)
  15. def bottombar_auto_delete_file_on_change(instance: BottomBar, **kwargs):
  16. """
  17. Deletes old file from filesystem
  18. when corresponding `icon` object is updated
  19. with new file.
  20. """
  21. if not instance.pk:
  22. return False
  23. try:
  24. old_file = BottomBar.objects.get(pk=instance.pk).icon
  25. except BottomBar.DoesNotExist:
  26. return False
  27. new_file = instance.icon
  28. if not old_file == new_file and old_file:
  29. if os.path.isfile(old_file.path):
  30. os.remove(old_file.path)
  31. @receiver(pre_delete, sender=Setting)
  32. def setting_auto_delete_file_on_delete(instance: Setting, **kwargs):
  33. """
  34. Deletes file from filesystem
  35. when corresponding `Settings` object is deleted.
  36. """
  37. if instance.page_image.path.endswith(instance.page_image.field.default):
  38. return False
  39. if instance.page_image:
  40. if os.path.isfile(instance.page_image.path):
  41. os.remove(instance.page_image.path)
  42. @receiver(pre_save, sender=Setting)
  43. def setting_auto_delete_file_on_change(instance: Setting, **kwargs):
  44. """
  45. Deletes old file from filesystem
  46. when corresponding `page_image` object is updated
  47. with new file.
  48. """
  49. if not instance.pk:
  50. return False
  51. try:
  52. old_file = Setting.objects.get(pk=instance.pk).page_image
  53. except Setting.DoesNotExist:
  54. return False
  55. if old_file.path.endswith(instance.page_image.field.default):
  56. return False
  57. new_file = instance.page_image
  58. if not old_file == new_file:
  59. if os.path.isfile(old_file.path):
  60. os.remove(old_file.path)