2

我尝试将实例的多个图像上传到不同的子文件夹。但是我还需要重命名每个上传的文件,所以我为 upload_to 字段实现了一个函数,如下所示。

class MyModel(models.Model):
    code = models.CharField()
    logo = models.FileField(upload_to=get_path)
    cover = models.FileField(upload_to=get_path)

def get_path(instance, filename):
    ext = filename.split('.')[-1]
    new_name = "%s.%s" % (slughifi(filename), ext)
    return new_name

但是,我不确定如何将图像划分为子文件夹logoscover_images 最好将参数传递给 get_path 函数,例如

    ...
    logo = models.FileField(upload_to=get_path("logos/"))
    cover = models.FileField(upload_to=get_path("cover_images/"))
    ...

我是否需要为每个文件字段编写不同的 upload_to 函数?

4

1 回答 1

0

我想不是,

你可以像这样使用它:

upload_to=lambda s,f: MyModel.upload_to(s,f,your_custom_path)


@classmethod
def upload_to(cls, obj, filename, custom_path):
    name,extension = os.path.splitext(filename)
    new_name = "%s.%s" % (slughifi(filename), extension)
    return "{}{}".format(custom_path, new_name)
于 2014-09-15T07:28:32.603 回答