Django testing model with ImageField

Solution 1:

For future users, I've solved the problem. You can mock an ImageField with a SimpleUploadedFile instance.

test.py

from django.core.files.uploadedfile import SimpleUploadedFile

newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')

Solution 2:

You can use a temporary file, using tempfile. So you don't need a real file to do your tests.

import tempfile

image = tempfile.NamedTemporaryFile(suffix=".jpg").name

If you prefer to do manual clean-up, use tempfile.mkstemp() instead.