Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 933
dfrankow Avatar asked Jun 08 '15 01:06

dfrankow


People also ask

What is datefield in Django forms?

DateField in Django Forms is a date field, for taking input of dates from user. The default widget for this input is DateInput. It Normalizes to: A Python datetime.date object. It validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format. DateField has one optional arguments:

What is a Timezone-aware DateTime object in Django?

A timezone-aware DateTime object simply means that it has a tzinfo attribute. Django conveniently provides timezone support via its utils module; i.e. to convert a DateTime object from above snippet:

How do I handle dates in Django forms?

The DateField (documentation) class in the django.forms module in the Django web framework provides a mechanism for safely handling dates, but not times, as input from an HTTP POST request. The request is typically generated by an HTML form created from a Django web application. Example 1 from django-filter

How do I create a birth date field in Django?

from django import forms class UserForm (forms.Form): birth_date= forms.DateField (label='What is your birth date?', widget=forms.SelectDateWidget) So, we have a form named UserForm. In this form, we create a field named birth_date. This form field is of type DateField.


1 Answers

@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'
like image 158
Maziyar Mk Avatar answered Jan 02 '23 10:01

Maziyar Mk