본문 바로가기

Python/Django

[Django] ImageField 저장 시 이름 변경하기

728x90

Django 코드 작성 중에 ImageField를 통해 이미지 저장 시 이름이 파일명 그대로 들어가는 것을 임의의 이름으로 바꾸고 싶을 때 사용할 수 있는 방법입니다.

 

우선 아래의 코드는 project 폴더 안에 utils.py 파일을 만든 후에 작성한 것입니다.

 

import os
from uuid import uuid4

def rename_imagefile_to_uuid(instance, filename):
        upload_to = f'media/foods/{instance}'
        ext = filename.split('.')[-1]
        uuid = uuid4().hex

        if instance:
            filename = '{}_{}.{}'.format(uuid, instance, ext)
        else:
            filename = '{}.{}'.format(uuid, ext)
        
        return os.path.join(upload_to, filename)

 

랜덤 이름을 생성할 uuid와 파일 경로를 합쳐줄 os를 가져와줍니다. 위의 함수에서 instance는 model 정의 시 사용할 수 있는 __str__(self) 함수의 반환 값과 동일합니다. 따라서 모델에 slug 필드를 만들어놓으면 slug에 맞게 폴더를 생성하여 이미지를 저장할 수 있게 됩니다.

 

 from <프로젝트 이름>.utils import rename_imagefile_to_uuid
 
 ...
 	image = models.ImageField(upload_to=rename_imagefile_to_uuid, max_length=255)
 ...

 

경로를 설정해주는 함수를 작성하였으니 models.py에 해당 함수를 가져와주고 원하는 이미지 필드의 upload_to 파라미터를 rename_imagefile_to_uuid 함수로 설정해줍니다.

 

    def __str__(self):
        return self.slug

 

이전에 설명하였듯이 instance에는 __str__의 반환 값이 들어가게 되므로 상황에 맞게 __str__을 설정해주면 됩니다.

728x90