问题
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