Browse Source

building books with pdfs

master
Mohsen Taba 4 months ago
parent
commit
663d9998ec
  1. 55
      apps/library/management/commands/populate_books.py
  2. 3
      entrypoint.sh
  3. BIN
      seeds/pdf/e-book.pdf

55
apps/library/management/commands/populate_books.py

@ -1,7 +1,8 @@
""" """
Django Management Command: populate_books Django Management Command: populate_books
This command creates 20 book objects with related categories and collections.
This command creates 20 book objects with related categories and collections,
including thumbnails and a dummy PDF file.
Usage: Usage:
python manage.py populate_books python manage.py populate_books
@ -17,30 +18,37 @@ import os
from django.core.files import File # Import File wrapper from django.core.files import File # Import File wrapper
class Command(BaseCommand): class Command(BaseCommand):
help = 'Create 20 book objects with categories and collections'
help = 'Create 20 book objects with categories, collections, and a PDF file'
def handle(self, *args, **options): def handle(self, *args, **options):
# 1. DELETE OLD DATA (This handles your requirement to clean up first)
# 1. DELETE OLD DATA
self.stdout.write(self.style.WARNING('Deleting existing books...')) self.stdout.write(self.style.WARNING('Deleting existing books...'))
deleted_count = Book.objects.all().delete()[0] deleted_count = Book.objects.all().delete()[0]
self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_count} existing books')) self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_count} existing books'))
# Setup Paths
# 2. SETUP PATHS
base_dir = settings.BASE_DIR base_dir = settings.BASE_DIR
# Ensure this matches where your source images actually are
seeds_path = os.path.join(base_dir, 'seeds', 'images')
# List of filenames inside seeds/images/
# Make sure these files exist!
# Image Paths
seeds_images_path = os.path.join(base_dir, 'seeds', 'images')
image_filenames = [ image_filenames = [
'lib-book1.png', 'lib-book2.png', 'lib-book3.png', 'lib-book4.png' 'lib-book1.png', 'lib-book2.png', 'lib-book3.png', 'lib-book4.png'
] ]
# PDF Path
pdf_path = os.path.join(base_dir, 'seeds', 'pdf', 'e-book.pdf')
# Check if PDF exists before starting
if not os.path.exists(pdf_path):
self.stdout.write(self.style.ERROR(f'CRITICAL: PDF not found at {pdf_path}'))
return
# 3. GET OR CREATE LANGUAGE
language, created = Language.objects.get_or_create( language, created = Language.objects.get_or_create(
code='en', defaults={'name': 'English'} code='en', defaults={'name': 'English'}
) )
# ... (Your book_data list remains the same, I'm hiding it for brevity) ...
# 4. DATA DEFINITION
book_data = [ book_data = [
{ {
'title': 'To Kill a Mockingbird', 'title': 'To Kill a Mockingbird',
@ -380,14 +388,14 @@ class Command(BaseCommand):
}, },
] ]
# 2. CREATE NEW DATA
# 5. CREATE NEW DATA
created_books = [] created_books = []
for idx, book_info in enumerate(book_data): for idx, book_info in enumerate(book_data):
try: try:
slug = slugify(book_info['title']) slug = slugify(book_info['title'])
# Create the book instance (WITHOUT the image first)
# Create the book instance (WITHOUT the image/file first)
book = Book( book = Book(
title=book_info['title'], title=book_info['title'],
slug=slug, slug=slug,
@ -409,18 +417,25 @@ class Command(BaseCommand):
pin=True, pin=True,
) )
# HANDLE THE IMAGE (The Magic Step)
# Pick an image filename
# HANDLE THE IMAGE
img_name = image_filenames[idx % len(image_filenames)] img_name = image_filenames[idx % len(image_filenames)]
img_full_path = os.path.join(seeds_path, img_name)
img_full_path = os.path.join(seeds_images_path, img_name)
if os.path.exists(img_full_path): if os.path.exists(img_full_path):
with open(img_full_path, 'rb') as f: with open(img_full_path, 'rb') as f:
# This copies the file from /seeds/ to /media/
# Copy to media folder
book.thumbnail.save(img_name, File(f), save=False) book.thumbnail.save(img_name, File(f), save=False)
else: else:
self.stdout.write(self.style.WARNING(f"Image not found: {img_full_path}")) self.stdout.write(self.style.WARNING(f"Image not found: {img_full_path}"))
# HANDLE THE PDF (NEW LOGIC)
# We rename the PDF to match the slug to ensure unique filenames in media
pdf_filename = f"{slug}.pdf"
if os.path.exists(pdf_path):
with open(pdf_path, 'rb') as pdf_f:
# Copy to media folder
book.book_file.save(pdf_filename, File(pdf_f), save=False)
# Now save the book to DB # Now save the book to DB
book.save() book.save()
created_books.append(book) created_books.append(book)
@ -428,16 +443,14 @@ class Command(BaseCommand):
self.stdout.write(self.style.SUCCESS(f'✓ Created: {book.title}')) self.stdout.write(self.style.SUCCESS(f'✓ Created: {book.title}'))
except Exception as e: except Exception as e:
self.stdout.write(self.style.ERROR(f'Error: {e}'))
self.stdout.write(self.style.ERROR(f'Error creating book {book_info["title"]}: {e}'))
# Category IDs and Collection IDs
category_ids = [1, 2, 3, 4, 5, 15, 16, 17, 18, 19, 20]
# 6. RELATIONS
category_ids = [1, 2, 3, 4, 15, 16, 17, 18, 19, 20]
collection_ids = [1, 2, 3, 4, 5, 6, 13, 14, 15] collection_ids = [1, 2, 3, 4, 5, 6, 13, 14, 15]
created_books = []
self.stdout.write(self.style.SUCCESS('Starting book creation...'))
self.stdout.write(self.style.SUCCESS('Starting relation assignment...'))
# Connect books with categories # Connect books with categories
self.stdout.write(self.style.SUCCESS('\nConnecting books to categories...')) self.stdout.write(self.style.SUCCESS('\nConnecting books to categories...'))

3
entrypoint.sh

@ -8,6 +8,7 @@ python manage.py collectstatic --noinput
# python manage.py populate_books # python manage.py populate_books
# python manage.py populate_book_reference # python manage.py populate_book_reference
# python manage.py populate_refrence_images # python manage.py populate_refrence_images
python manage.py populate_article
# python manage.py populate_article
python manage.py populate_books
exec "$@" exec "$@"

BIN
seeds/pdf/e-book.pdf

Loading…
Cancel
Save