I defined a model:
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.TimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model"""
return self.text
I retrieve them in a view:
topics = Topic.objects.order_by("date-added")
I've been working on this project for a while now and the topics were displayed in the right order, but at some point I noticed that they're placed not in chronological order.
I tried to see the dates (in Django shell):
for topic in Topic.objects.order_by("date_added"):
print(topic, topic.date_added.strftime("%d.%m.%Y $H:%M:%S"))
The result:
Hip-hop 01.01.1900 10:39:27
Rap2 01.01.1900 10:40:17
Chess 01.01.1900 15:45:32
Rock Climbing 01.01.1900 15:45:43
Programming 01.01.1900 15:51:18
Boxing 01.01.1900 18:21:59
Rap 01.01.1900 20:50:58
It shows, they're all added in the 1st Jan of 1900.
How to configure the date in Django so it displays it right?
You used date_added = models.TimeField(auto_now_add=True)
, but ideally it should be date_added = models.DateTimeField(auto_now_add=True)
.
I think 1st of Jan 1900 is the default date as timefield only accepts time values, therefore it sets the default date to 1st of Jan 1900.
TimeField - here you can see timefield is used for time.
DateTimeField - datetime should be used here for storing both the date and time of the date_added
field.