Skip to content

Commit

Permalink
Create ImageField files from a callable
Browse files Browse the repository at this point in the history
Allow dynamic creation of ``factory.django.ImageField`` fields
by passing a function that returns an image file object.
  • Loading branch information
tomleo committed Sep 14, 2016
1 parent b78e3aa commit b83fa89
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/orms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ Extra fields
and keep its filename
:param file from_file: Use the contents of the provided file object; use its filename
if available
:param func from_func: Use function that returns a file object
:param str filename: The filename for the ImageField
:param int width: The width of the generated image (default: ``100``)
:param int height: The height of the generated image (default: ``100``)
Expand Down
10 changes: 8 additions & 2 deletions factory/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,10 @@ def _make_data(self, params):
def _make_content(self, params):
path = ''

if params.get('from_path') and params.get('from_file'):
_content_params = [params.get('from_path'), params.get('from_file'), params.get('from_func')]
if len([p for p in _content_params if p]) > 1:
raise ValueError(
"At most one argument from 'from_file' and 'from_path' should "
"At most one argument from 'from_file', 'from_path', and 'from_func' should "
"be non-empty when calling factory.django.FileField."
)

Expand All @@ -221,6 +222,11 @@ def _make_content(self, params):
content = django_files.File(f)
path = content.name

elif params.get('from_func'):
func = params['from_func']
content = django_files.File(func())
path = content.name

else:
data = self._make_data(params)
content = django_files.base.ContentFile(data)
Expand Down

0 comments on commit b83fa89

Please sign in to comment.