Advertisement
shoaib-santo

DJango CheatSheet

Nov 25th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. Auto Delete Image from Database
  2. ===============================
  3.  
  4. from django.db import models
  5. from django.db.models.signals import post_delete
  6. from django.dispatch import receiver  # Make sure this is imported
  7. import os
  8.  
  9. class Portfolio(models.Model):  # Corrected model name capitalization
  10.     title = models.CharField(max_length=100)
  11.     description = models.CharField(max_length=1000)
  12.     image = models.ImageField(upload_to='portfolios/')
  13.  
  14.     def save(self, *args, **kwargs):
  15.         try:
  16.             # Check if the instance already exists in the database
  17.             old_instance = Portfolio.objects.get(pk=self.pk)
  18.             if old_instance.image and old_instance.image != self.image:
  19.                 # Delete the old image file
  20.                 if os.path.isfile(old_instance.image.path):
  21.                     os.remove(old_instance.image.path)
  22.         except Portfolio.DoesNotExist:
  23.             pass  # If instance does not exist, no old file to delete
  24.         super().save(*args, **kwargs)
  25.  
  26.     def __str__(self):
  27.         return self.title
  28.  
  29. @receiver(post_delete, sender=Portfolio)  # Ensure this refers to the correct model
  30. def delete_image_file(sender, instance, **kwargs):
  31.     if instance.image:
  32.         if os.path.isfile(instance.image.path):
  33.             os.remove(instance.image.path)
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement