Django ImageField change file name on upload

前端 未结 5 1574
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 04:35

Upon saving me model \'Products\' I would like the uploaded image to be named the same as the pk for example 22.png or 34.gif I don\'t want to change the format of the image jus

5条回答
  •  佛祖请我去吃肉
    2021-01-30 04:44

    Django 1.7 and newer won't make migration with function like this. Based on answer by @miki725 and this ticket, you need to make your function like this:

    import os
    from uuid import uuid4
    from django.utils.deconstruct import deconstructible
    
    @deconstructible
    class UploadToPathAndRename(object):
    
        def __init__(self, path):
            self.sub_path = path
    
        def __call__(self, instance, filename):
            ext = filename.split('.')[-1]
            # get filename
            if instance.pk:
                filename = '{}.{}'.format(instance.pk, ext)
            else:
                # set filename as random string
                filename = '{}.{}'.format(uuid4().hex, ext)
            # return the whole path to the file
            return os.path.join(self.sub_path, filename)
    
    FileField(upload_to=UploadToPathAndRename(os.path.join(MEDIA_ROOT, 'upload', 'here'), ...)
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题