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?
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:
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:
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
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.
@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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With