wagtail - 批量上传和创建带有 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":
...
]
我怀疑其他人过去曾遇到过这个问题。我继续感谢社区和您的所有贡献。干杯!
解决方案
让它工作。
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.")
推荐阅读
- python - 创建矩阵时列索引超出范围
- javascript - 创建类别模板出了什么问题
- r - 对于每个显示“x”的单元格,我可以找到一列中两行之间的差异吗?
- cocoa - macOS Big Sur 忽略 ffi-1.12.2,因为它的扩展未构建
- javascript - 如何从对象数组中获取第一个重复的对象?
- html - 对齐不移动文本和滚动文本在同一行
- css - 切换菜单使导航文本下降
- python - 在 Flask 中,如何从具有相对路径引用的子目录运行另一个 python 应用程序?
- php - composer 命令在 Laravel 安装程序中出错
- css - 将鼠标悬停在标题中的迷你购物车上