Search code examples
djangodjango-modelsdjango-testing

Django is appending unwanted characters to Imagefield name attribute


I am writing a test for my Imagefield model that checks its relative path name, but it is not passing because the __str__ method returns the file path + some unwanted characters. For example, a file created as test_image.png is returned as test_image_ak0LKei.png, despite the fact that I am explicitly defining the file name. Every time a new file is created the appended part changes, it can return test_image_HqOXJc4.png, for example.

This only happens when I am creating a dummy image file for the tests. When I upload a real image in Django's admin, it just returns the file path without any modifications. I am using Sqlite for tests and Postgres for the development, as the development database is in Heroku and it does not allow table creation

I tried to change how I create the dummy file, like using a bytes object, using b64decode() with SimpleUploadedFile() from django, but the results are the same.

My models:

class Image(models.Model):
    image = models.ImageField(upload_to='post_images/')
    alt_tag = models.CharField(max_length=125, blank=True)

def __str__(self):
    return self.image.name

My test. The last thing I tried is using the static method below:

class ImageTestCase(TestCase):
    @staticmethod
    def get_image_file(name='test_image.png', ext='png', size=(50, 50), color=(256, 0, 0)):
        file_obj = BytesIO()
        image = PIL_IMAGE.new("RGBA", size=size, color=color)
        image.save(file_obj, ext)
        file_obj.seek(0)
    return File(file_obj, name=name)

def setUp(self):
    test_image = Image.objects.create(
        image = self.get_image_file(),
        alt_tag = 'test image'
    )

def test_image_category(self):
    image1 = Image.objects.get(id=1)
    self.assertEqual(str(image1), 'post_images/test_image.jpg')

The failed test result:

Traceback (most recent call last):
  File "/home/edumats/Projects/blog/blog/posts/test_models.py", line 67, in test_image_category
    self.assertEqual(str(image1), 'post_images/test_image.png')
AssertionError: 'post_images/test_image_ak0LKei.png' != 'post_images/test_image.png'
- post_images/test_image_ak0LKei.png
?                       --------
+ post_images/test_image.png

Solution

  • When you upload two files with the same name within the same folder, django automatically renames the last uploaded file by adding a string of alphanumeric characters.

    The same would also happen with a real image (try uploading the same image twice!)