Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中更改上载时的文件名和存储位置_Python_Django_File Upload_Django Models_Storage - Fatal编程技术网

Python 如何在django中更改上载时的文件名和存储位置

Python 如何在django中更改上载时的文件名和存储位置,python,django,file-upload,django-models,storage,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

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

我有

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\u文件
字段更改为:

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

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


有没有办法解决这个问题

我认为您的问题是需要在文件名前加上子文件夹,然后返回。在数据库中,文件名应该是从
静态URL
媒体URL
到文件的相对路径

下面是一个例子,我为文件名生成一个UUID,并将其放入名为
app\u images
的子文件夹中。


但是,我必须为不同的类编写两个单独的函数,对吗?@PaulBernhardWagner这可以工作,但您可能不必这样做,您可以检查实例参数的类型,即如果type(instance)=bar else“restaurant”,则路径='bar'。我没有亲自尝试过,但它可能会起作用。
image_file = models.ImageField(upload_to=name_func,null=True, storage=bar)
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)