首页 > 解决方案 > 如何从管理命令将图像导入 Wagtail?

问题描述

我有一个与此类似的数据模型,用于存储位置列表和与每个位置关联的照片库:

@register_snippet
class Location(modelcluster.models.ClusterableModel):
    name = models.CharField()

class LocationPhoto(Orderable):
    location = ParentalKey(
        Location,
        on_delete=models.CASCADE,
        related_name='gallery'
    )

    image = models.ForeignKey(
        'wagtailImage.Image',
        on_delete=models.CASCADE,
        related_name='+',
    )

    alt = models.CharField(verbose_name='Alt text')

我想创建一个管理命令,可以从 JSON 文件和图像文件夹批量加载这些位置及其关联的画廊。

我如何在 Python 中导入图像,以便它们最终出现在media/目录中,就像我通过 Wagtail 管理 UI 上传它们一样?

标签: djangowagtail

解决方案


假设你有一个文件路径,我会给你一个例子

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

class Command(BaseCommand):
    help = "Import an image from filepath"

def add_arguments(self, parser):
    parser.add_argument('filepath')

def handle(self, *args, **options):
    # You child will be added to the parent
    parent = YourParentObject.objects.first()
    your_object = YourObject(title="Something",...)
    if exists(options["filepath"]):
        # Open the file as binary
        with open(filepath,"rb") as imagefile:
            # Gets the name of the file
            filename = filepath.split("/")[-1]
            image = Image(file=ImageFile(BytesIO(imagefile.read()), name=filename))
            image.save()
            your_object.your_image_field = image
            # now you can save your model
    parent.add_child(instance=your_object)

推荐阅读