Tuesday, October 27, 2020

Get datetime now, not at server initialisation

I have a function that uses the current date to set up a file path
for uploaded images:


def upload_path():
dtnow = datetime.now(timezone.utc)
dtstr = '{:%Y/%m/%d/%H/%M/%S}'.format(dtnow)
print('dtstr: ')
dtstr = 'images/items/' + dtstr
return dtstr

class Image(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
#file = ImageField(_('image'), upload_to='images')
file = ImageField(_('image'), upload_to=upload_path())


The problem is that when the Image class calls 'upload_path' the
datetime portion of this is always the runserver initialisation time,
rather than the time when 'upload_path' is called/used.

How to fix this?


-- Clive

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/AE06A649-0B34-46F2-9FD0-0386B2843D93%40indx.co.uk.

No comments:

Post a Comment