【问题标题】:How to make FactoryBoy's ImageField generate image before save() is called?如何在调用 save() 之前让 FactoryBoy 的 ImageField 生成图像?
【发布时间】:2014-09-12 10:40:38
【问题描述】:

主题

现在(Factory Boy 版本 2.4.1。)使用此代码:

class ImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Image

    image = factory.django.ImageField(width=1024, height=768)

image 在保存时将是None,因此如果Image 模型覆盖了save 并且它与image 一起运行,它将失败。这正是我的情况。

那么 - 如何在save 调用之前生成图像?

【问题讨论】:

  • 添加您的解决方法作为答案。它会让其他人更容易找到:)

标签: python django factory-boy


【解决方案1】:

我找到了解决方法:

from django.core.files.base import ContentFile

class ImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Image

    image = factory.LazyAttribute(
            lambda _: ContentFile(
                factory.django.ImageField()._make_data(
                    {'width': 1024, 'height': 768}
                ), 'example.jpg'
            )
        )

【讨论】:

  • 这似乎可行,但是在尝试操作 image.file.content_type 时,会引发 AttributeError: 'ContentFile' object has no attribute 'content_type'
  • @JulienKieffer 你能解决这个问题吗?我也有同样的问题
  • from django.core.files.base import ContentFiledocs.djangoproject.com/en/dev/ref/files/file/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2012-05-16
  • 2015-03-30
  • 1970-01-01
  • 2010-10-19
  • 2011-07-24
  • 2018-08-10
相关资源
最近更新 更多