'How to Handle Create, Update and Delete Image with Django Signals?
I have these Models, I want to change the Name of the Photos in this Pattern (ProductName-ImageId.jpg) I want help in changing the Name of the file, in Update and delete it? is it the Best Practice for doing This?
models:
class Product(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, null=False, blank=False)
describtion = models.TextField()
price = models.FloatField()
inventory = models.PositiveIntegerField()
created_time = models.DateTimeField(auto_now_add=True)
last_updated_time = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return self.name
def get_absolute_url(self)->str:
return reverse("shop:product", kwargs={"pk": self.pk})
@property
def photos(self):
return ProductImage.objects.filter(product=self)
@property
def base_photo(self):
return self.photos.first().image
class ProductImage(models.Model):
id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to="products/photos")
product = models.ForeignKey(Product, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.product.name
signals:
from django.db.models.signals import post_delete , post_save
from django.dispatch import receiver
from .models import ProductImage
import os
from pathlib import Path
from django.conf import settings
# This Work On Delete
@receiver(post_delete, sender=ProductImage)
def my_handler(sender,instance:ProductImage, **kwargs):
# Delete the Image after delete the Entry
Path(instance.image.path).unlink()
@receiver(post_save, sender=ProductImage)
def my_handler(sender,instance:ProductImage,created, **kwargs):
print()
print(instance.image.name)
print(instance.image.path)
print()
if created:
old_path =Path( instance.image.path)
instance.image.name = f"{instance.product.name}-{instance.id}.jpg"
new_path = settings.BASE_DIR / f"media/products/photos/{instance.image.name}"
old_path.rename(new_path)
instance.save()
print(instance.image.path)
the two Methods work but when I rename the File the Path Change before Signal :
E:\Programming\Python\Django Projects\Django-shop-app\media\products\photos\c-d-x-PDX_a_82obo-unsplash.jpg
after Signal :
E:\Programming\Python\Django Projects\Django-shop-app\media\Headphones-16.jpg
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
