How to use DateField in a Django form in a timezone-aware way?

4.7k views Asked by At

I have a DateField in a Django 1.8 model, something like:

from django.db import models
birth_date = models.DateField()

When it goes onto a form, I get back a 'naive' object:

birth_date = the_form.cleaned_data['birth_date']

Printing birth_date in the debugger:

ipdb> birth_date
datetime.date(2015, 6, 7)

Then when this thing is saved to a database, I get a warning, as the documentation promises:

RuntimeWarning: SQLite received a naive datetime (2015-06-08 01:08:21.470719) while time zone support is active.

I've read some articles on this, and I am still confused. What should I do with this date?

Should I convert it to a DateTime, make it timezone-aware, then back into a Date? Should I make the model a DateTimeField and abandon DateFields? What are best practices here?

2

There are 2 answers

0
kalo On

I think that you can try to use make_aware to convert the date to aware format. From make_aware django documentation:

make_aware(value, timezone=None, is_dst=None)

Returns an aware datetime that represents the same point in time as value in timezone, value being a naive datetime.

This should fix the warning:

from django.utils import timezone

birth_date = timezone.make_aware(the_form.cleaned_data['birth_date'], timezone.get_default_timezone())
0
Maziyar Mk On

@kalo's answer didn't work for me, so I created this utility function from what ended up working for me based on his answer:

from django.utils import timezone
from django.utils.dateparse import parse_date
from django.utils.datetime_safe import time


def make_timezone_aware(date):
    return timezone.make_aware(timezone.datetime.combine(parse_date(date), time.min))

Combining the date with a 00:00 time solved the following errors:

  • 'datetime.date' object has no attribute 'tzinfo'
  • 'str' object has no attribute 'tzinfo'