[Fixed]-Django SimpleUploadedFile with Python 3

14👍

This SO answer helped me solve it.

In the end, this is the updated working test code:

def test_create(self):
    (abs_dir_path, filename) = os.path.split(self.image)

    with open(self.image) as infile:
        _file = SimpleUploadedFile(filename, infile.read())
        attachment = Attachment.objects.create(
            model_id=self.model.id,
            file=_file
        )

        self.assertIsInstance(attachment, Attachment)
        self.assertEqual(
            attachment.filename,
            self.image.split('/')[-1] # test-mountains.jpg
        )

Leave a comment