首页 > 解决方案 > 批量上传和创建带有 wagtail 图像的页面(迁移)

问题描述

我正在创建一个带有 wagtail 的网站来替换某人现有的 weebly 网站。重新创建数百个页面实例中的每一个并为这些页面中的每一个上传每个图像都需要数小时。

我已经有了我需要的页面模型,而且我的网站看起来很像 wagtail 文档中的入门教程。我想知道如何编写脚本来迁移此内容。在搜索答案时,我会找到有关以编程方式创建模型的更多信息,而不是将内容本身推送到我的 wagtail 网站。

我已经抓取了旧站点并保存了所有需要的图像,并且我有以下格式的 JSON 数据:

[
    {
        "page_name": "first page",
        "images": [
            {
                "url": "http://www.a.com/final-1.jpg",
                "filename": "final-1.jpg",
                "caption": "A caption"
            },
            {
                "url": "http://www.a.com/final-2.jpeg",
                "filename": "final-2.jpeg",
                "caption": ""
            }
        ],
        "body": "Body text goes here. "
    },
    {
        "page_name": "page 2",
        "images": 

...

]

我怀疑其他人过去曾遇到过这个问题。我继续感谢社区和您的所有贡献。干杯!

标签: wagtail

解决方案


让它工作。

data.json 存放在站点根目录下,import_content.py 存放在 blog/management/commands

然后运行pipenv run py manage.py import_content

from django.core.management.base import BaseCommand, CommandError
from blog.models import InstallationPage, GalleryImage, Gallery, InstallationMedium

from wagtail.images.models import Image
from django.core.files.images import ImageFile
from io import BytesIO

import json, os
from datetime import datetime
from slugify import slugify

class Command(BaseCommand):
    help = 'Importing pages and image content, for initial migration.'


    def handle(self, *args, **options):
        with open('data.json', 'r') as f:
            data = json.load(f)['data']
            for page in reversed(data):
                name=page['name']
                body=page['body']
                images=page['images']

                parent = Gallery.objects.first()

                new_page = InstallationPage(
                    title=name,
                    slug=slugify(name),
                    date=datetime.today(),
                    body=json.dumps([{'type': 'paragraph', 'value':body}]) if len(body) else None,
                    mediums=[InstallationMedium.objects.get(name='Painting')]
                    )
                self.stdout.write(f"Initialized page {name}")
                saved_images = []
                for img_data in images:
                    path = os.path.join(r"C:\path\to\image\files",img_data['filename'])

                    with open(path,"rb") as imagefile:

                        image = Image(file=ImageFile(BytesIO(imagefile.read()), name=img_data['filename']), title=name+'-'+img_data['filename'].rsplit('.',1)[0])
                        image.save()
                        gallery_image = GalleryImage(
                            image=image,
                            caption=img_data['caption']
                            )
                        saved_images.append(gallery_image)
                        self.stdout.write(f"    Saved image {img_data['filename']} to database")


                parent.add_child(instance=new_page)
                new_page.save_revision()

                new_page.gallery_images=saved_images
                new_page.save_revision().publish()

                self.stdout.write(f"        Attached images to {name}.")

                self.stdout.write(f"Published page {name} with {str(len(images))} images.")

推荐阅读