2016-06-09 1 views
1

업로드시 이미지 이름과 저장 위치를 ​​변경하고 싶습니다.django에서 업로드시 파일 이름과 저장 위치를 ​​변경하는 방법

내가

def name_func(instance, filename): 
    blocks = filename.split('.') 
    ext = blocks[-1] 
    filename = "%s.%s" % (instance.id, ext) 
    return filename 

class Restaurant(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4) 
    image_file = models.ImageField(upload_to=name_func,null=True) 

class Bar(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4) 
    image_file = models.ImageField(upload_to=name_func,null=True) 

이 미디어 폴더에있는 모든 이미지 파일을 업로드하고 이름으로 그것을 인스턴스의 ID를 제공합니다 있습니다.

이제 이미지 파일을 서로 다른 두 개의 하위 폴더에 업로드하려고합니다. 그러나 지금이 올바른 폴더 구조에서 파일을 저장

image_file = models.ImageField(upload_to=name_func,null=True, storage=fs_restaurant) 

image_file = models.ImageField(upload_to=name_func,null=True, storage=bar) 

:

fs_restaurant = FileSystemStorage(location='media/restaurant') 
fs_bar = FileSystemStorage(location='media/bar') 

다음 image_file 필드를 변경 : 그래서 시스템 filestorage를 사용하여 시도 , 관리자의 패널에있는 링크를 클릭하면 제대로 연결되지 않습니다. 이 기능은 분명히 name_func이지만,이를 수정하는 방법이 있는지 궁금합니다. 문서에서 저장소 클래스에서 명명 함수를 찾을 수 없습니다.

해결 방법에 대한 아이디어가 있으십니까?

답변

1

당신의 문제는 파일 이름에 하위 폴더를 추가하고 그것을 반환해야한다는 것입니다. 데이터베이스에서 파일 이름은 STATIC_URL 또는 MEDIA_URL에서 파일의 상대 경로 여야합니다.

다음은 파일 이름에 대한 UUID를 생성하여 app_images이라는 하위 폴더에 넣는 예제입니다.

def unique_filename(instance, filename): 
    path = 'app_images' 
    filetype = os.path.splitext(instance.image.name)[1] 
    new_filename = "{}{}".format(uuid.uuid4().hex, filetype) 
    while AppImage.objects.filter(image__contains=new_filename).exists(): 
     new_filename = "{}{}".format(uuid.uuid4().hex, filetype) 
    instance.filename = filename 
    return os.path.join(path, new_filename) 
+0

그렇다면 다른 클래스에 대해 두 개의 별도 함수를 작성해야합니다. – Tom

+1

@PaulBernhardWagner 작동하지만 작동하지 않을 수도 있습니다. 유형 (인스턴스) == Bar else 'restaurant'인 경우 인스턴스 인수의 유형, 즉'path = 'bar'를 잠재적으로 확인할 수 있습니다. 나는 이것을 개인적으로 시도하지 않았지만 효과가있을 수있다. – ARJMP

+0

이 작동합니다. 죄송합니다. 수락하는 것을 잊어 버렸습니다. 감사합니다. – Tom

관련 문제