You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.5 KiB
63 lines
2.5 KiB
import os
|
|
from django.core.management.base import BaseCommand
|
|
from django.conf import settings
|
|
from django.core.files import File
|
|
from apps.hadis.models import BookVolume, BookReferenceImage
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Assigns static/images/image.png to all BookVolumes in the database'
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
'--force',
|
|
action='store_true',
|
|
help='Force re-assign even if the volume already has an image',
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
force = options.get('force', False)
|
|
|
|
# 1. Locate the image file
|
|
image_path = os.path.join(settings.BASE_DIR, 'static', 'images', 'image.png')
|
|
if not os.path.exists(image_path):
|
|
self.stdout.write(self.style.ERROR(f"Source image not found at: {image_path}"))
|
|
return
|
|
|
|
self.stdout.write(f"Source image found at: {image_path}")
|
|
|
|
volumes = BookVolume.objects.all()
|
|
total_volumes = volumes.count()
|
|
self.stdout.write(f"Found {total_volumes} volumes in the database.")
|
|
|
|
created_count = 0
|
|
updated_count = 0
|
|
|
|
for vol in volumes:
|
|
# Check if volume already has an image
|
|
existing_images = BookReferenceImage.objects.filter(book_volume=vol)
|
|
|
|
if existing_images.exists() and not force:
|
|
continue
|
|
|
|
with open(image_path, 'rb') as f:
|
|
if existing_images.exists() and force:
|
|
# Overwrite the first existing image
|
|
img_instance = existing_images.first()
|
|
img_instance.image.save('image.png', File(f), save=True)
|
|
updated_count += 1
|
|
else:
|
|
# Create a new BookReferenceImage entry
|
|
img_instance = BookReferenceImage(
|
|
book_reference=vol.book_reference,
|
|
book_volume=vol,
|
|
order=0,
|
|
description=[{"language_code": "fa", "text": f"تصویر پیشفرض {vol.title or ''}"}]
|
|
)
|
|
img_instance.image.save('image.png', File(f), save=True)
|
|
created_count += 1
|
|
|
|
self.stdout.write(
|
|
self.style.SUCCESS(
|
|
f"Successfully processed volumes: created {created_count}, updated {updated_count} (force={force})."
|
|
)
|
|
)
|