Opened 37 hours ago

Closed 33 hours ago

#35771 closed Bug (duplicate)

Bugs: models.DateField value has not been assigned correct date value when auto_now_add is set

Reported by: Ambitiont109 Owned by:
Component: Database layer (models, ORM) Version: 5.0
Severity: Normal Keywords: auto_now
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Ambitiont109)

class Vote(models.Model):
    class Points(models.IntegerChoices):
        Top = 3
        Second = 2
        Third = 1

    points: models.IntegerField = models.IntegerField(choices=Points.choices, default=Points.Top)
    date: models.DateField = models.DateField(auto_now_add=True)


from django.utils import timezone

timezone.now() # datetime.datetime(2024, 9, 18, 3, 7, 3, 608467, tzinfo=datetime.timezone.utc)
timezone.now().date()# datetime.date(2024, 9, 18)

import datetime
datetime.datetime.now() #datetime.datetime(2024, 9, 17, 23, 7, 14, 337114) My local pc timezone is UTC-4
datetime.date.today() #datetime.date(2024, 9, 17)

v = Vote(points=Vote.Points.Top)

v.save()
v.date # Expected value is datetime.date(2024, 9, 18) since I enabled USE_TZ=True in settings.py
       # current value is  datetime.date(2024, 9, 17)

"""
I figured it out myself and in `pre_save` function of models.DateField class, we should use timezone.now().date() instead of datetime.date.today()
""

Change History (2)

comment:1 by Ambitiont109, 37 hours ago

Description: modified (diff)

comment:2 by Sarah Boyce, 33 hours ago

Resolution: duplicate
Status: newclosed

Duplicate of #32320

Note: See TracTickets for help on using tickets.
Back to Top