我有这样的模特:
class Obs(models.Model):
date = models.DateTimeField(auto_now_add=False, verbose_name='Date')
description = models.TextField(verbose_name='Description')
content = models.FileField(verbose_name='File', upload_to='%Y/%m/%d')
category = models.ForeignKey(ObsType, related_name='Type', verbose_name='type')
user = models.ForeignKey(User, verbose_name='User')
我需要将'upload_to'路径设置为'date'字段,但此日期不是当前日期。 我该怎么做?
更新
我用以下函数解决它:
def get_upload_to(instance, filename):
date = unicode(instance)
date = date.split()[0] # to delete Time
date = date.split('-')
return '%s/%s/%s/%s' % (date[0], date[1], date[2], filename)
在我的情况下,日期表示为2014-01-04。 如果是2014/01/04将会出错。
答案 0 :(得分:4)
您应该使用自定义方法指定upload_to
路径,如下所示:
def get_obs_upload_path(instance, filename):
my_custom_date = datetime.now()
return '%s/%s' % (my_custom_date, filename)
class Obs(models.Model):
date = models.DateTimeField(auto_now_add=False, verbose_name='Date')
description = models.TextField(verbose_name='Description')
content = models.FileField(verbose_name='File', upload_to=get_obs_upload_path)
category = models.ForeignKey(ObsType, related_name='Type', verbose_name='type')
user = models.ForeignKey(User, verbose_name='User')