Browse Source

populating book references

master
Mohsen Taba 4 months ago
parent
commit
c1182d6731
  1. 183
      apps/hadis/management/commands/populate_book_reference.py
  2. 2
      apps/hadis/models/hadis.py
  3. 3
      entrypoint.sh

183
apps/hadis/management/commands/populate_book_reference.py

@ -0,0 +1,183 @@
"""
Django Management Command: populate_book_references
Creates 10 Islamic Hadith BookReference objects with related images.
Usage: python manage.py populate_book_references
"""
import os
import random
from django.core.management.base import BaseCommand
from django.core.files import File
from django.conf import settings
from apps.hadis.models import BookReference, BookReferenceImage
class Command(BaseCommand):
help = 'Create 10 Islamic Hadith BookReference objects with images'
def handle(self, *args, **options):
# ---------------------------------------------------------
# 1. CLEANUP: Delete existing data
# ---------------------------------------------------------
self.stdout.write(self.style.WARNING('Deleting existing BookReferences...'))
count = BookReference.objects.all().delete()[0]
self.stdout.write(self.style.SUCCESS(f'✓ Deleted {count} existing records.'))
# ---------------------------------------------------------
# 2. SETUP PATHS
# ---------------------------------------------------------
base_dir = settings.BASE_DIR
seeds_path = os.path.join(base_dir, 'seeds', 'images')
# We will cycle through book1.png to book5.png
image_filenames = [f'book{i}.png' for i in range(1, 6)]
# Verify directory exists
if not os.path.exists(seeds_path):
self.stdout.write(self.style.ERROR(f"Directory not found: {seeds_path}"))
return
# ---------------------------------------------------------
# 3. DEFINE DATA (10 Islamic Hadith Books)
# ---------------------------------------------------------
references_data = [
{
"title_en": "Sahih al-Bukhari",
"title_fa": "صحیح بخاری",
"desc": "One of the most authentic collections of Hadith in Sunni Islam.",
"publisher": "Darussalam",
"year": "846",
"vol": "9"
},
{
"title_en": "Al-Kafi",
"title_fa": "الکافی",
"desc": "The most significant collection of Shia Hadith by Kulayni.",
"publisher": "Dar al-Kutub al-Islamiyya",
"year": "941",
"vol": "8"
},
{
"title_en": "Sahih Muslim",
"title_fa": "صحیح مسلم",
"desc": "Considered the second most authentic book after Bukhari.",
"publisher": "Dar-us-Salam",
"year": "875",
"vol": "7"
},
{
"title_en": "Nahj al-Balagha",
"title_fa": "نهج البلاغه",
"desc": "A collection of sermons, letters, and sayings of Imam Ali (AS).",
"publisher": "Ansariyan Publications",
"year": "1010",
"vol": "1"
},
{
"title_en": "Sunan Abu Dawood",
"title_fa": "سنن ابوداوود",
"desc": "A collection of Hadith focusing on legal matters (Fiqh).",
"publisher": "Maktabah al-Assriya",
"year": "888",
"vol": "5"
},
{
"title_en": "Man La Yahduruhu al-Faqih",
"title_fa": "من لا یحضره الفقیه",
"desc": "For him who is not in the presence of a jurisprudent - Shia collection.",
"publisher": "Jami'at al-Mudarisin",
"year": "991",
"vol": "4"
},
{
"title_en": "Jami` at-Tirmidhi",
"title_fa": "جامع ترمذی",
"desc": "Known for categorizing Hadith by authenticity (Sahih, Hasan, Da'if).",
"publisher": "Dar al-Gharb al-Islami",
"year": "892",
"vol": "6"
},
{
"title_en": "Tahdhib al-Ahkam",
"title_fa": "تهذیب الاحکام",
"desc": "A classic Shia Hadith collection by Shaykh Tusi.",
"publisher": "Dar al-Adwa",
"year": "1067",
"vol": "10"
},
{
"title_en": "Sunan an-Nasa'i",
"title_fa": "سنن نسائی",
"desc": "Highly regarded collection with very few weak hadiths.",
"publisher": "Dar al-Ma'rifa",
"year": "915",
"vol": "6"
},
{
"title_en": "Bihar al-Anwar",
"title_fa": "بحار الانوار",
"desc": "The most comprehensive collection of Shia traditions by Majlisi.",
"publisher": "Al-Wafa",
"year": "1698",
"vol": "110"
}
]
# ---------------------------------------------------------
# 4. CREATE RECORDS
# ---------------------------------------------------------
self.stdout.write("Starting creation process...")
for index, data in enumerate(references_data):
try:
# A. Create the BookReference
book_ref = BookReference.objects.create(
title=[
{"language_code": "en", "text": data["title_en"]},
{"language_code": "fa", "text": data["title_fa"]}
],
description=[
{"language_code": "en", "text": data["desc"]},
{"language_code": "fa", "text": f"توضیحات درباره {data['title_fa']}"}
],
language=[
{"language_code": "en", "text": "Arabic/English"},
{"language_code": "fa", "text": "عربی/فارسی"}
],
isbn=f"978-{random.randint(100,999)}-{random.randint(1000,9999)}-{index}",
volume=data["vol"],
year_of_publication=data["year"],
number_page=random.randint(300, 1500),
# Slug is handled by model .save() method automatically
publisher=[
{"language_code": "en", "text": data["publisher"]},
{"language_code": "fa", "text": data["publisher"]}
],
rate=round(random.uniform(4.0, 5.0), 2)
)
# B. Create and Save the Image (BookReferenceImage)
# Cycle through images: 0->book1, 1->book2... 5->book1
img_name = image_filenames[index % len(image_filenames)]
img_path = os.path.join(seeds_path, img_name)
if os.path.exists(img_path):
with open(img_path, 'rb') as f:
# Create the Image object
ref_image = BookReferenceImage(
book_reference=book_ref,
order=0,
description=[{"language_code": "en", "text": f"Cover of {data['title_en']}"}]
)
# Save file content (THIS COPIES IT TO MEDIA VOLUME)
ref_image.image.save(img_name, File(f), save=True)
else:
self.stdout.write(self.style.WARNING(f"Image not found: {img_name}"))
self.stdout.write(self.style.SUCCESS(f"✓ Created: {data['title_en']}"))
except Exception as e:
self.stdout.write(self.style.ERROR(f"Error creating {data['title_en']}: {e}"))
self.stdout.write(self.style.SUCCESS('\n=========================================='))
self.stdout.write(self.style.SUCCESS(f'Successfully populated {len(references_data)} BookReferences!'))

2
apps/hadis/models/hadis.py

@ -377,7 +377,7 @@ class ReferenceImage(models.Model):
verbose_name_plural = _('Reference Images') verbose_name_plural = _('Reference Images')
def __str__(self): def __str__(self):
return f'{self.reference.title[0]["text"]}-{self.id}'
return f'{self.reference.book_reference.title[0]["text"]}-{self.id}'
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if ReferenceImage.objects.filter(reference=self.reference, priority=self.priority).exists(): if ReferenceImage.objects.filter(reference=self.reference, priority=self.priority).exists():

3
entrypoint.sh

@ -5,6 +5,7 @@ python manage.py migrate
# python manage.py seed_images # python manage.py seed_images
python manage.py collectstatic --noinput python manage.py collectstatic --noinput
python manage.py populate_books
# python manage.py populate_books
python manage.py populate_book_reference
exec "$@" exec "$@"
Loading…
Cancel
Save