传递参数在Django upload_to功能(Passing parameter to uploa

2019-10-20 23:13发布

我尝试实例的多张图片上传到不同的子文件夹。 但我需要让我实现一个功能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功能,每个文件中的字段?

Answer 1:

我觉得不行,

哟可以使用它是这样的:

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)


文章来源: Passing parameter to upload_to function in Django