How to make FactoryBoy's ImageField generate image before save() is called?
Asked Answered
H

1

14

Subj.

Right now (Factory Boy ver. 2.4.1.) with this code:

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

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

image will be None at save time, so if the Image model has save overridden and its operates with the image, it will fail. And thats exactly my case.

So - how to make image generated before save call?

Hara answered 12/9, 2014 at 10:40 Comment(1)
Add your workaround as an answer instead. It will make it easier for other people to find :)Brindled
H
26

I've found a workaround:

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'
            )
        )
Hara answered 13/9, 2014 at 10:6 Comment(3)
That seems to work, but when trying to manipulate image.file.content_type, AttributeError: 'ContentFile' object has no attribute 'content_type' is raisedDespair
@JulienKieffer were you able to solve this? I'm having the same problemFreighter
from django.core.files.base import ContentFile docs.djangoproject.com/en/dev/ref/files/file/…Chronaxie

© 2022 - 2024 — McMap. All rights reserved.