Files
shopback/blog/signals.py
Beyhan Oğur d9f1ea341e first commit
2026-04-26 22:27:56 +03:00

53 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.files.base import ContentFile
from .models import Post
@receiver(pre_save, sender=Post)
def update_post_thumb(sender, instance, **kwargs):
"""
Post kaydedilmeden önce, image alanı doluysa thumb'ı da güncelle
"""
if instance.image:
# Yeni kayıt veya image güncellenmiş mi kontrol et
should_update_thumb = False
if instance.pk:
try:
old_instance = Post.objects.get(pk=instance.pk)
# Image değişmişse thumb'ı da güncelle
if str(old_instance.image) != str(instance.image):
should_update_thumb = True
except Post.DoesNotExist:
# Kayıt bulunamadı, yeni kayıt gibi davran
should_update_thumb = True
else:
# Yeni kayıt (pk yok)
should_update_thumb = True
if should_update_thumb and hasattr(instance.image, 'file'):
# Image dosyasını thumb alanına kopyala
try:
# Image dosyasının içeriğini oku
instance.image.file.seek(0)
image_content = instance.image.file.read()
instance.image.file.seek(0)
# Dosya adını al
image_name = instance.image.name.split('/')[-1]
# Thumb alanına kaydet
instance.thumb.save(
image_name,
ContentFile(image_content),
save=False
)
except Exception as e:
print(f"Thumb oluşturma hatası: {e}")
import traceback
traceback.print_exc()