Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Auto Delete Image from Database
- ===============================
- from django.db import models
- from django.db.models.signals import post_delete
- from django.dispatch import receiver # Make sure this is imported
- import os
- class Portfolio(models.Model): # Corrected model name capitalization
- title = models.CharField(max_length=100)
- description = models.CharField(max_length=1000)
- image = models.ImageField(upload_to='portfolios/')
- def save(self, *args, **kwargs):
- try:
- # Check if the instance already exists in the database
- old_instance = Portfolio.objects.get(pk=self.pk)
- if old_instance.image and old_instance.image != self.image:
- # Delete the old image file
- if os.path.isfile(old_instance.image.path):
- os.remove(old_instance.image.path)
- except Portfolio.DoesNotExist:
- pass # If instance does not exist, no old file to delete
- super().save(*args, **kwargs)
- def __str__(self):
- return self.title
- @receiver(post_delete, sender=Portfolio) # Ensure this refers to the correct model
- def delete_image_file(sender, instance, **kwargs):
- if instance.image:
- if os.path.isfile(instance.image.path):
- os.remove(instance.image.path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement