2
0

load_initial_data.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import os
  2. from django.conf import settings
  3. from django.core.files.storage import FileSystemStorage, default_storage
  4. from django.core.management import call_command
  5. from django.core.management.base import BaseCommand
  6. from wagtail.models import Page, Site
  7. class Command(BaseCommand):
  8. def _copy_files(self, local_storage, path):
  9. """
  10. Recursively copy files from local_storage to default_storage. Used
  11. to automatically bootstrap the media directory (both locally and on
  12. cloud providers) with the images linked from the initial data (and
  13. included in MEDIA_ROOT).
  14. """
  15. directories, file_names = local_storage.listdir(path)
  16. for directory in directories:
  17. self._copy_files(local_storage, path + directory + "/")
  18. for file_name in file_names:
  19. with local_storage.open(path + file_name) as file_:
  20. default_storage.save(path + file_name, file_)
  21. def handle(self, **options):
  22. fixtures_dir = os.path.join(settings.PROJECT_DIR, "base", "fixtures")
  23. fixture_file = os.path.join(fixtures_dir, "bakerydemo.json")
  24. print("Copying media files to configured storage...") # noqa: T201
  25. local_storage = FileSystemStorage(os.path.join(fixtures_dir, "media"))
  26. self._copy_files(local_storage, "") # file storage paths are relative
  27. # Wagtail creates default Site and Page instances during install, but we already have
  28. # them in the data load. Remove the auto-generated ones.
  29. if Site.objects.filter(hostname="localhost").exists():
  30. Site.objects.get(hostname="localhost").delete()
  31. if Page.objects.filter(title="Welcome to your new Wagtail site!").exists():
  32. Page.objects.get(title="Welcome to your new Wagtail site!").delete()
  33. call_command("loaddata", fixture_file, verbosity=0)
  34. call_command("update_index", verbosity=0)
  35. call_command("rebuild_references_index", verbosity=0)
  36. print( # noqa: T201
  37. "Awesome. Your data is loaded! The bakery's doors are almost ready to open..."
  38. )