first commit
This commit is contained in:
52
blog/signals.py
Normal file
52
blog/signals.py
Normal file
@@ -0,0 +1,52 @@
|
||||
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()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user