从 wagtail 外部上传 Wagtail 图像

Uploading Wagtail images from outside of wagtail

在无法子类化的 Django 模型中 Page,我想将现有的 ImageField 转换为使用 Wagtail 图像。我已将字段重新定义为:

avatar = models.ForeignKey(
    'wagtailimages.Image', null=True, on_delete=models.SET_NULL, related_name='+'
)

用户需要能够将图像上传到他们的个人资料视图。在 Django 视图的 forms.py 中,我有:

avatar = forms.ImageField(
    label='Your Photo', required=False,
    error_messages={'invalid': "Image files only"}, widget=forms.FileInput())

当我将图像上传到视图时,它崩溃了:

Cannot assign "<InMemoryUploadedFile: filename.jpg (image/jpeg)>":
"UserProfile.avatar" must be a "Image" instance.

我很确定问题出在表单中的字段定义上,但我不知道正确的定义应该是什么。

我知道我需要手动将图像附加到 UserProfile 和 Collection,但需要先解决这个错误。还是尝试在 non-WT 模型中使用单个 WT 字段是个坏主意?谢谢

这里的问题是模型中的 avatar ForeignKey 字段需要接收 wagtailimages.Image 模型的实例。表单上的 ImageField 无法提供此功能 - 它仅提供一个文件对象。为了使这项工作有效,您需要设置您的表单(我假设它是一个 ModelForm)以在创建您自己的模型的同时创建 wagtailimages.Image 对象。应该可以使用自定义 save 方法执行此操作,如下所示:

  • avatar = forms.ImageField 重命名为与 avatar 模型字段不冲突的名称,例如 avatar_image
  • 确保 avatar_image 包含在您的 ModelForm 的 fields 定义中,但 avatar 没有。此时,avatar_image 只是表单上的一个额外字段,与模型无关。
  • 在 ModelForm 上定义以下 save 方法:

    from wagtail.images.models import Image
    
    def save(self, commit=False):
        if not commit:
            raise Exception("This form doesn't support save(commit=False)")
    
        # build the instance for this form, but don't save it to the db yet
        instance = super(MyForm, self).save(commit=False)
    
        # create the Image object
        avatar = Image.objects.create(
            file=self.cleaned_data['avatar_image'],
            title="Image title"
            # you may need to add more fields such as collection to make it a valid image...
        )
    
        # attach the image to your final model, and save
        instance.avatar = avatar
        instance.save()
        return instance