python - 如何在django中更改上传文件的名称和存储位置

标签 python django file-upload django-models storage

我想更改图像名称及其上传时的存储位置。

我有

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 作为名称。

现在我希望将图像文件上传到两个不同的子文件夹中。所以我尝试使用系统文件存储:

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

然后将 image_file 字段更改为:

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)

现在,这会将文件保存在正确的文件夹结构中,但是,当我单击管理面板中的链接时,它的链接不正确。这显然是针对 name_func 函数的,但我想知道是否有办法纠正它?在文档中我找不到存储类中的命名函数。

关于如何解决这个问题有什么想法吗?

最佳答案

我认为你的问题是你需要将子文件夹添加到你的文件名中并返回它。在数据库中,文件名应该是 STATIC_URLMEDIA_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)

关于python - 如何在django中更改上传文件的名称和存储位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737587/

相关文章:

Python itertool 变体,达到内存最大值

python - 根据多个条件获取 NumPy 数组的连续元素组

python - 局部变量也是类变量

django - 是否可以在没有请求对象的情况下在 Django 中使用上下文处理器?

python - Virtualenv 未从主管 AWS Elasticbeanstalk 激活

javascript - 使用 Html5 文件 api 确定未知内容类型

python - 在numpy中将int数组转换为字符串数组而不截断

python - Django - 尽管在 urls.py 中但未找到播放器 URL

php无法无错误上传大文件

jsf - 无论如何在JSF中通过ajax上传文件?