|
| 1 | +import os |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.core.files.storage import FileSystemStorage, default_storage |
| 5 | +from django.core.management import call_command |
| 6 | +from django.core.management.base import BaseCommand |
| 7 | + |
| 8 | +from wagtail.models import Page, Site |
| 9 | + |
| 10 | + |
| 11 | +class Command(BaseCommand): |
| 12 | + def _copy_files(self, local_storage, path): |
| 13 | + """ |
| 14 | + Recursively copy files from local_storage to default_storage. Used |
| 15 | + to automatically bootstrap the media directory (both locally and on |
| 16 | + cloud providers) with the images linked from the initial data (and |
| 17 | + included in MEDIA_ROOT). |
| 18 | + """ |
| 19 | + directories, file_names = local_storage.listdir(path) |
| 20 | + for directory in directories: |
| 21 | + self._copy_files(local_storage, path + directory + "/") |
| 22 | + for file_name in file_names: |
| 23 | + with local_storage.open(path + file_name) as file_: |
| 24 | + default_storage.save(path + file_name, file_) |
| 25 | + |
| 26 | + def handle(self, **options): |
| 27 | + fixtures_dir = os.path.join(settings.PROJECT_ROOT, "..", "fixtures") |
| 28 | + fixture_file = os.path.join(fixtures_dir, "wagtail.org-demo.json") |
| 29 | + |
| 30 | + print("Copying media files to configured storage...") # noqa: T201 |
| 31 | + local_storage = FileSystemStorage(os.path.join(fixtures_dir, "media")) |
| 32 | + self._copy_files(local_storage, "") # file storage paths are relative |
| 33 | + |
| 34 | + # Wagtail creates default Site and Page instances during install, but we already have |
| 35 | + # them in the data load. Remove the auto-generated ones. |
| 36 | + if Site.objects.filter(hostname="localhost").exists(): |
| 37 | + Site.objects.get(hostname="localhost").delete() |
| 38 | + if Page.objects.filter(title="Welcome to your new Wagtail site!").exists(): |
| 39 | + Page.objects.get(title="Welcome to your new Wagtail site!").delete() |
| 40 | + |
| 41 | + call_command("loaddata", fixture_file, verbosity=0) |
| 42 | + call_command("update_index", verbosity=0) |
| 43 | + call_command("rebuild_references_index", verbosity=0) |
| 44 | + |
| 45 | + print( # noqa: T201 |
| 46 | + "Done!" |
| 47 | + "\n" |
| 48 | + "Now here's a haiku to celebrate:" |
| 49 | + "\n\n" |
| 50 | + " data flows in streams\n" |
| 51 | + " placeholder shapes come alive\n" |
| 52 | + " your site awakes" |
| 53 | + ) |
0 commit comments