ImageField上传位置的文件名可以是什么? [英] What can be the filename of uploading location for ImageField?
本文介绍了ImageField上传位置的文件名可以是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当我使用 cloth_image
创建服装
模型时,图像就会上传到 upload_location
。
Whenever I create Cloth
Model with cloth_image
, the image uploads to upload_location
.
我的问题是 instance.id
返回 None
,因为该实例尚未创建。 什么是ImageField的最佳上载位置?
My problem is instance.id
returns None
because the instance is not yet created. What can be the best upload_location for ImageField?
def upload_location(instance, filename):
new_id = instance.id
ext = filename.split('.')[-1]
return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) # <- Right Here!
class Cloth(models.Model):
cloth_image = models.ImageField(upload_to=upload_location,
null=True,
blank=True)
我正在使用AWS S3。
I'm using AWS S3.
推荐答案
如果您想要唯一的文件名,我认为您可以使用 uuid
为此,例如
if you want unique filename, i think you can use uuid
for it, for example
import uuid
import os
def get_file_path(instance, filename):
base_dir = 'clothes'
user.id = str(instance.user.id)
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join(base_dir, user_id, filename)
这篇关于ImageField上传位置的文件名可以是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文