Reputation: 21
I'm using timezone.now() (django.utils impor timezone) to set the initial date of my model. But, the timezone.now() is fixed to the time when i set the server up, and doesnt change. How can i fix this?
I wanna that the timezone.now() return the datetime when the user is creating an object and not the time when i run the server.
Upvotes: 2
Views: 659
Reputation: 1601
The commonly used model extensions is used for this particular case with TimeStampedModel
from django_extensions.db.models import TimeStampedModel
class MyModel(TimeStampedModel):
pass
The migration will create created
and updated
that get handled exactly as you would expect.
Upvotes: 0
Reputation: 477308
You should pass a reference to the function to it, so:
from django.db import models
from django.utils import timezone
class MyModel(models.Model):
created_at = models.DateTimeField(default=timezone.now)
But likely you want to use auto_now_add=True
[Django-doc], which will also make the field non-editable:
from django.db import models
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
Upvotes: 0