Passing parameter to upload_to function in Django

流过昼夜 提交于 2020-01-04 06:08:10

问题


I try to upload multiple images of an instance to different sub folders. But I need to rename each uploaded file as well so I implement a function for upload_to field as below.

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

However, I'm not sure how I can divide images to subfolders like logos and cover_images It'd better if I pass a parameter to get_path function like

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

Do I need to write different upload_to functions for each file field?


回答1:


i think no,

yo can use it like this:

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)


来源:https://stackoverflow.com/questions/25842458/passing-parameter-to-upload-to-function-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!