Wednesday, October 28, 2020

Re: Get datetime now, not at server initialisation


On Oct/27/2020, Clive Bruton wrote:

> I have a function that uses the current date to set up a file path for
> uploaded images:
> ********************
> def upload_path():


> 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?

For what I remeber (I use FileField usually but this is noto relevant I
hope) you should do:

def upload_path(instance, filename):
# you have access to the instance (object model Image in your case)
# and the filename that the user used to upload it
# and this is executed on the upload time
return your_new_file_name

In the model:
file = ImageField(_('image'), upload_to=upload_path)

note that upload_path is a callable: it gets called on the upload time.
In your code it was called on initialization time.

Some time ago I had a similar code that caused a bug: in a ListView the
"queryset = " is executed on startup time. For a dynamic one I should
have used get_queryset() method.

Carles Pina i Estany

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
To view this discussion on the web visit

No comments:

Post a Comment