0

I have a model where I want the name field to be a string representation of the timestamp, and another field to be the actual time stamp. Here is my model code:

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S"))
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

Then I go in the django shell and enter this:

>>> import models
>>> models.Image(image='images/rock.png').save()

This works but the only problem is the two times do not align. For example, I get name = 20191201-143119 and create_date = 2019-12-01 14:32:11.445474.

How can I get these two datetimes to be the same?

dwvldg
  • 293
  • 4
  • 12
  • Hi, @dwvldg. This [answer](https://stackoverflow.com/questions/2771676/django-datetime-issues-default-datetime-now) might help you – Eliakin Costa Dec 01 '19 at 14:47

2 Answers2

1

I've linked an answer will help you understand what is happening. Achieving what you want is quite simple though.

models.py

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255)
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

    def save(self, *args, **kwargs):
        if not self.name: 
            self.name = datetime.now().strftime("%Y%m%d-%H%M%S")
        super(Image, self).save(*args, **kwargs) 
Eliakin Costa
  • 930
  • 6
  • 16
1

This is a pretty common gotcha in Django's world. The post mentioned by @eliakin-costa discuss this problem, although his solution works I wouldn't recommend overriding save method to get this behavior as it's easier to create a function (keeping decoupled and explicit):

from django.db import models
from django.utils import timezone

def default_image_name():
   return timezone.now().strftime("%Y%m%d-%H%M%S")

class Image(models.Model):
    name = models.CharField(max_length=255, default=default_image_name)
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

By the way, did you take a look at this docs (upload_to also accepts a callable) ? Do you really need a name column in your table?

gmacro
  • 397
  • 3
  • 6