""" Django management command to seed mock data for hadith book references. Place this file in: yourapp/management/commands/seed_books.py Usage: python manage.py seed_books """ import os from pathlib import Path from django.core.management.base import BaseCommand from django.core.files.base import ContentFile from django.utils.text import slugify from apps.hadis.models.reference import ( BookReference, BookReferenceImage, BookAuthor, BookAttribute ) class Command(BaseCommand): help = 'Seed the database with mock hadith book reference data' def add_arguments(self, parser): parser.add_argument( '--clear', action='store_true', help='Clear existing data before seeding', ) def handle(self, *args, **options): if options['clear']: self.stdout.write(self.style.WARNING('Clearing existing data...')) BookAttribute.objects.all().delete() BookReferenceImage.objects.all().delete() BookAuthor.objects.all().delete() BookReference.objects.all().delete() self.stdout.write(self.style.SUCCESS('Data cleared successfully!')) # Create authors first authors_data = [ {"name": "Imam Muhammad al-Bukhari"}, {"name": "Imam Muslim ibn al-Hajjaj"}, {"name": "Imam Abu Dawood as-Sijistani"}, {"name": "Imam At-Tirmidhi"}, {"name": "Imam Ibn Majah"}, {"name": "Imam Ahmad ibn Hanbal"}, {"name": "Imam Al-Hakim"}, {"name": "Imam Ad-Daraqutni"}, ] authors = {} for author_data in authors_data: author, created = BookAuthor.objects.get_or_create( name=author_data['name'] ) authors[author_data['name']] = author if created: self.stdout.write(self.style.SUCCESS(f'Created author: {author.name}')) # Create book references books_data = [ { "title": "Sahih al-Bukhari", "description": "The most authentic collection of hadith, compiled by Imam Muhammad al-Bukhari. Contains 7,563 ahadith.", "language": "Arabic", "isbn": "978-1-86043-009-6", "volume": "9 volumes", "year_of_publication": "1870", "number_page": 1200, "publisher": "Dar al-Kutub al-Ilmiyah", "rate": 5.00, "authors": ["Imam Muhammad al-Bukhari"], "image_order": 1, "attributes": { "Collection Type": "Hadith Compilation", "Number of Hadith": "7,563", "Classification": "6 Books", "Authenticity Grade": "Sahih (Authentic)", "Compilation Period": "16 years", } }, { "title": "Sahih Muslim", "description": "Second most authentic hadith collection compiled by Imam Muslim ibn al-Hajjaj. Contains 9,200 traditions.", "language": "Arabic", "isbn": "978-1-86043-010-2", "volume": "5 volumes", "year_of_publication": "1875", "number_page": 1500, "publisher": "Dar Ihya at-Turath al-Arabi", "rate": 4.95, "authors": ["Imam Muslim ibn al-Hajjaj"], "image_order": 2, "attributes": { "Collection Type": "Hadith Compilation", "Number of Hadith": "9,200", "Classification": "43 Books", "Authenticity Grade": "Sahih (Authentic)", "Unique Hadith": "Approximately 4,000", } }, { "title": "Sunan Abu Dawood", "description": "A comprehensive collection of hadith containing jurisprudential material, compiled by Imam Abu Dawood as-Sijistani.", "language": "Arabic", "isbn": "978-1-86043-011-9", "volume": "4 volumes", "year_of_publication": "1880", "number_page": 1400, "publisher": "Islamic Digital Library", "rate": 4.80, "authors": ["Imam Abu Dawood as-Sijistani"], "image_order": 3, "attributes": { "Collection Type": "Sunan (Practice)", "Number of Hadith": "5,274", "Focus": "Jurisprudential Traditions", "Number of Books": "43", "Authenticity Grade": "Hasan to Sahih", } }, { "title": "Jami' at-Tirmidhi", "description": "A major collection of hadith compiled by Imam At-Tirmidhi with his commentary and grading of narrations.", "language": "Arabic", "isbn": "978-1-86043-012-6", "volume": "5 volumes", "year_of_publication": "1892", "number_page": 1350, "publisher": "Dar ar-Risalah al-Alamiyah", "rate": 4.85, "authors": ["Imam At-Tirmidhi"], "image_order": 4, "attributes": { "Collection Type": "Jami (Comprehensive)", "Number of Hadith": "3,956", "Notable Feature": "Grades each hadith", "Categories": "63 Chapters", "Authenticity Grade": "Various Grades", } }, { "title": "Sunan Ibn Majah", "description": "A collection of hadith compiled by Imam Ibn Majah, one of the Six Canonical Hadith Collections.", "language": "Arabic", "isbn": "978-1-86043-013-3", "volume": "2 volumes", "year_of_publication": "1888", "number_page": 900, "publisher": "Dar Ihya al-Kutub al-Arabiyah", "rate": 4.75, "authors": ["Imam Ibn Majah"], "image_order": 5, "attributes": { "Collection Type": "Sunan (Practice)", "Number of Hadith": "4,341", "Number of Books": "32", "Notable Content": "Includes rare narrations", "Authenticity Grade": "Mixed - requires verification", } }, ] books = {} for book_data in books_data: # Extract author names author_names = book_data.pop('authors', []) image_order = book_data.pop('image_order', 1) attributes_dict = book_data.pop('attributes', {}) # Create or get the book book, created = BookReference.objects.get_or_create( title=book_data['title'], defaults=book_data ) if created: self.stdout.write(self.style.SUCCESS(f'Created book: {book.title}')) else: # Update existing book for key, value in book_data.items(): setattr(book, key, value) book.save() self.stdout.write(self.style.WARNING(f'Updated book: {book.title}')) books[book.title] = book # Add authors to book for author_name in author_names: author = authors.get(author_name) if author: book.authors.add(author) # Add book image image_path = self._get_image_path(image_order) if image_path and os.path.exists(image_path): # Check if image already exists for this book if not book.images.exists(): with open(image_path, 'rb') as img_file: image_name = f'book{image_order}.png' book_image = BookReferenceImage.objects.create( book_reference=book, order=1, description=f"Cover image for {book.title}" ) book_image.image.save( image_name, ContentFile(img_file.read()), save=True ) self.stdout.write( self.style.SUCCESS(f'Added image to: {book.title}') ) else: self.stdout.write( self.style.WARNING( f'Image not found at {image_path} for {book.title}' ) ) # Add attributes for attr_title, attr_value in attributes_dict.items(): attribute, created = BookAttribute.objects.get_or_create( book_reference=book, title=attr_title, defaults={'value': attr_value} ) if created: self.stdout.write( self.style.SUCCESS( f'Added attribute: {attr_title} to {book.title}' ) ) self.stdout.write( self.style.SUCCESS( f'\nāœ“ Successfully seeded {len(books)} books with all relations!' ) ) self._print_summary() def _get_image_path(self, book_number): """ Find the image file for the given book number. Checks multiple possible locations. """ possible_paths = [ Path('seeds/images') / f'book{book_number}.png', Path('seed_data/images') / f'book{book_number}.png', Path('static/images') / f'book{book_number}.png', Path('.') / 'seeds' / 'images' / f'book{book_number}.png', ] for path in possible_paths: if path.exists(): return path return None def _print_summary(self): """Print a summary of created data""" self.stdout.write("\n" + "="*60) self.stdout.write(self.style.SUCCESS("DATABASE SUMMARY")) self.stdout.write("="*60) books_count = BookReference.objects.count() authors_count = BookAuthor.objects.count() images_count = BookReferenceImage.objects.count() attributes_count = BookAttribute.objects.count() self.stdout.write(f"šŸ“š Total Books: {books_count}") self.stdout.write(f"āœļø Total Authors: {authors_count}") self.stdout.write(f"šŸ–¼ļø Total Images: {images_count}") self.stdout.write(f"šŸ·ļø Total Attributes: {attributes_count}") self.stdout.write("="*60 + "\n")