首页 > 解决方案 > django - Dynamic upload path including month and year not working

问题描述

I want to upload file with dynamic path i.e. YEAR/MONTH//FILES

To achieve this i am using below code

def user_directory_path(instance, filename):
    return '%Y/%B/{0}/files/{1}'.format(instance.retailer.retailer_id, filename)

class FileUpload(models.Model):
    file = models.FileField(upload_to=user_directory_path)
    car = models.ForeignKey(CarMaster, on_delete=models.CASCADE, default=None)

class CarMaster(models.Model):
    user = models.ForeignKey(User,default=None,on_delete=models.CASCADE)
    car_id = models.PositiveIntegerField(unique=True)
    car_name = models.CharField(max_length=1000)

Folder structure getting created is as below

media\%Y\%B\100000\files

Here %Y and %B should be replaced by Year and Month name which is not happening.

Is there a way we can achieve this.

标签: djangodjango-viewsdjango-formsdjango-file-upload

解决方案


我能够通过可调用的 upload_to 实现

def local_directory_path(instance, filename):
    now = instance.file_month
    return '{0}/{1}/{2}/{3}'.format(now.strftime('%Y'),now.strftime('%B'),instance.car.car_id, filename)

推荐阅读