django - 如何从管理命令将图像导入 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 上传它们一样?
解决方案
假设你有一个文件路径,我会给你一个例子
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)
推荐阅读
- javascript - 如何使用在 Angular 中隐藏和显示密码值的按钮切换文本
- python - Linux 上 VS Code 中的 Python 路径
- c++ - 用于测量函数花费时间的 API 设计
- mysql - Mysql查询到两列的百分比
- c# - 排序集中的最大连续数
- databricks - dbutils.notebook.run 不选择保存在 DBFS 位置的运行笔记本
- python - 如何在 atom 上指定模块(django)的版本?
- sql-server - 'float' (DT_R8) 数据类型上的 SSIS 截断错误
- python - 我的代码以某种方式乘以 0.5 倍,我不知道为什么
- javascript - 如何在 Javascript 中检查和更改砖块的状态?