4👍
✅
First of all DateTimeField supports auto updating like this:
created = models.DateTimeField(editable=False, auto_now_add=True) # Only on creation
updated = models.DateTimeField(editable=False, auto_now=True) # On every save
Secondly the RuntimeWarning you get, means that you have enabled in your
settings.py timezone aware datetime objects e.g you will see the following:
USE_TZ = True
When you do that, you have to treat datetime objects differently, you have to pass
explicitly a tzinfo
value.
# install the `pytz` module through pip or whatnot
from pytz import timezone
import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
# To show the time in Greece
athens = timezone('Europe/Athens')
print now.astimezone(athens)
For more info see the django docs and the pytz docs.
About the coercing to Unicode:
error, try doing this:
def __unicode__(self):
return unicode(self.id)
0👍
What I did to store now
on creation, was use the default
attribute of the DateTimeField, and Django’s now() wrapper like so:
from django.utils import timezone
ctime = models.DateTimeField(default=timezone.now)
Please note that this date is in UTC timezone, if you require some other time zone to be set, wrap timezone.now
in a lambda that calls localtime()
- [Django]-Query in ManyToMany relation
- [Django]-How to filter django-taggit top tags
- [Django]-Django how to open file in FileField
- [Django]-Should django templates name for each app be unique?
- [Django]-To Use Django-Haystack or not?
Source:stackexchange.com