Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Making (or having the option to make) factory.django.FileField non-post-generation #141
I have a use case where the file is interacted with just before saving to the database (I'm making a sha256 hash of the file and storing this). When using
Based on the way your code looks, it seems like it would probably be a little challenging to make FileField optionally post-generation (because it appears to be based on inheritance). Mainly, I'm curious if this is something that you would consider supporting, or if there is a good reason for forcing it to be post-generation. If it seems like an ok idea, I would consider contributing the PR for it, given your thoughts on an implementation.
Hi @ianawilson ,
Well, that would be quite interesting.
The core issue I have is "how do I get a real file-like object and/or a stream of bytes into a Django FileField, with a chosen filename" :)
It's been a while since I've looked at this, so I quickly refreshed myself on factory boy and my workaround. Apologies in advance if I'm totally overlooking something.
To refresh myself and make sure I'm being clear, I pulled together some code snippets from my project. My issue was that the data for the FileField was required by my Django model's
class MyModel(models.Model): # truncated example ... file = models.FileField() def save(self, *args, **kwargs): # code that uses self.file.read() self.generate_hash() super(MyModel, self).save(*args, **kwargs)
The FileField has no value when
class MyFactory(factory.django.DjangoModelFactory): # truncated example ... FACTORY_FOR = MyModel file = factory.django.FileField(data='data', filename='test__can_delete__mymodel') @classmethod def create(cls, *args, **kwargs): """ Workaround for FileField being a post generation attribute """ instance = cls.build(*args, **kwargs) instance.save() return instance
Is there a reason that FileField instantiation should be considered post-generation? I don't think that follows the same pattern as the Django's ORM, because I get the behavior I expect when I use
EDIT: Python syntax highlighting of examples