[Fixed]-DateTimeField received a naive datetime while time zone support is active

22👍

From the docs at: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#code

During development, you can turn such warnings into exceptions and get a traceback by adding the following to your settings file:

import warnings
warnings.filterwarnings(
    'error', r"DateTimeField .* received a naive datetime",
    RuntimeWarning, r'django\.db\.models\.fields')
👤dalore

2👍

You can implement your a log formatter and put trace back for warning messages in the logs using traceback.print_exception().

Refer to Fomatter docs at FormatException

You can also refer this, How do I use Django's logger to log a traceback when I tell it to?

👤Rohan

-2👍

This means that you enabled timezone support in django; but you passed it a datetime object that doesn’t have any time zone information attached to it.

If you want django’s timezone support, then datetime objects used should be timezone aware.

The documentation on timezone support provides a way to turn your datetime objects into those with timzeones.

-3👍

Django’s source tells you what just happened:

def get_prep_value(self, value):
    value = self.to_python(value)
    if value is not None and settings.USE_TZ and timezone.is_naive(value):
        # For backwards compatibility, interpret naive datetimes in local
        # time. This won't work during DST change, but we can't do much
        # about it, so we let the exceptions percolate up the call stack.
        warnings.warn(u"DateTimeField received a naive datetime (%s)"
                      u" while time zone support is active." % value,
                      RuntimeWarning)
        default_timezone = timezone.get_default_timezone()
        value = timezone.make_aware(value, default_timezone)
    return value

Leave a comment