All Articles Kinsa Creative

Unit Testing File Objects in Django with SimpleUploadedFile

SimpleUploadedFile is undocumented, but referenced in the Django documentation.

To use SimpleUploadedFile when unit testing a FileField such as

from django.db import models

class MyModel(models.Model):
    file = models.FileField(upload_to='somewhere')

Create a SimpleUploadedFile with Model Bakery, for example, in a test:

from model_bakery import baker

from django.core.files.uploadedfile import SimpleUploadedFile

#... some other code ...

    # note that the file content must be bytes
    file=SimpleUploadedFile('file.jpg', b"file_content", content_type='image/jpeg')

# ... some more code ...

You can now test code that references that file object.


Email us at