import os import random from django.core.management.base import BaseCommand from django.core.files import File from django.conf import settings # REPLACE 'your_app_name' with your actual app name from apps.hadis.models import Hadis, HadisReference, BookReference, ReferenceImage class Command(BaseCommand): help = 'Creates HadisReferences with random Books (IDs 34-43) and attaches ref1-4 images.' def handle(self, *args, **kwargs): self.stdout.write(self.style.WARNING('Starting Reference & Image creation...')) # 1. SETUP IMAGES PATH # --------------------------------------------------------- seeds_path = os.path.join(settings.BASE_DIR, 'seeds', 'images') image_files = ['ref1.png', 'ref2.png', 'ref3.png', 'ref4.png'] # Validate images exist for img in image_files: if not os.path.exists(os.path.join(seeds_path, img)): self.stdout.write(self.style.ERROR(f"Image not found: {os.path.join(seeds_path, img)}")) self.stdout.write(self.style.ERROR("Please create 'seeds/images' folder and add ref1.png to ref4.png.")) return # 2. FETCH SPECIFIC BOOK REFERENCES (IDs 34-43) # --------------------------------------------------------- target_ids = list(range(34, 44)) # range(34, 44) produces 34...43 book_references = list(BookReference.objects.filter(id__in=target_ids)) if not book_references: self.stdout.write(self.style.ERROR(f"No BookReferences found with IDs {target_ids}. Please check your database.")) return self.stdout.write(f"Found {len(book_references)} Book References to distribute randomly.") # 3. PROCESS HADIS RECORDS # --------------------------------------------------------- hadises = Hadis.objects.all() processed_count = 0 for hadis in hadises: # Pick a random book from the list random_book = random.choice(book_references) # A. Create HadisReference # We use get_or_create to prevent duplicates if run multiple times hadis_ref, created = HadisReference.objects.get_or_create( hadis=hadis, defaults={ 'book_reference': random_book, 'description': [ {"text": f"Reference from {random_book.title[0]['text']}", "language_code": "en"}, {"text": f"Ссылка из {random_book.title[0]['text']}", "language_code": "ru"} ] } ) # Only attach images if this reference was just created # (To avoid adding duplicate images if you run the script twice) if created: # B. Attach Images (ref1 - ref4) for index, img_name in enumerate(image_files): file_path = os.path.join(seeds_path, img_name) with open(file_path, 'rb') as f: ref_image = ReferenceImage( reference=hadis_ref, priority=index + 1 # 1, 2, 3, 4 ) # Save image with unique name prefix to avoid overwrite issues ref_image.thumbnail.save(f"{hadis.id}_{img_name}", File(f), save=True) processed_count += 1 if processed_count % 10 == 0: self.stdout.write(f"Processed references for {processed_count} Hadiths...") self.stdout.write(self.style.SUCCESS(f'Successfully created references for {processed_count} new Hadis records.'))