ImageField in the model

Requirements

pip (requirements.txt) : Pillow>=5.3.0,<5.4.0

permanant dependencies (added to dockerfile): jpeg-dev

temporary dependencies (added to dockerfile): musl-dev zlib zlib-dev

Add ImageField to model

1) Add ImageField to RecipeModel

2) Input to this field should be a file object

3) Have to specify upload_to function, which will take the file object and return a path

4) uuid is used to create a unique ID to the filename. Hence, when the same file is uploaded, it appears in different location

# to create unique id for files
import uuid
import os


def recipe_image_file_path(instance, filename):
    """ generate filepath for new image"""
    ext = filename.split('.')[-1]
    # creates a unique id for the filename
    filename = f'{uuid.uuid4()}.{ext}'

    return os.path.join('uploads/recipe/', filename)


class Recipe(models.Model):
    ...
    # Image field
    # calls a function to find the file path
    # Input to this field is a file object
    image = models.ImageField(null=True, upload_to=recipe_image_file_path)

Test

class ImageManagerTest(TestCase):

    # change image name with uuid for unique identification
    @patch('uuid.uuid4')
    def test_image_filename_uuid(self, mock_uuid):
        # mock the generated uuid with test uuid
        uuid = 'test-uuid'
        mock_uuid.return_value = uuid
        original_filename = 'myimage.jpg'
        file_path = models.recipe_image_file_path(None, original_filename)
        expected_path = f'uploads/recipe/{uuid}.jpg'

        self.assertEqual(file_path, expected_path)