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作为名字。
现在我想要图像文件上传到两个不同的子文件夹。所以,我尝试使用系统filestorage:
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
函数,但我想知道是否有一种方法来纠正?在文档中我找不到存储类中的命名函数。
关于如何解决这个问题的任何想法?
但后来我必须为不同的类写两个单独的函数,对吧? – Tom
@PaulBernhardWagner这会工作,但你可能不需要,你可以检查实例参数的类型,例如,如果type(instance)== Bar else'restaurant'',那么'path ='bar'。我没有亲自尝试过,但它可以工作。 – ARJMP
那个作品,对不起,忘了接受,谢谢!! – Tom