How to use DateField in Django time-based form?

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

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

When it moves to the form, I return a “naive” object:

 birth_date = the_form.cleaned_data['birth_date'] 

Printing the parent report in the debugger:

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

Then, when this thing is stored in the 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 read several articles about this, and I'm still confused. What should I do with this date?

Should I convert it to DateTime, make it hourly, and then go back to date? Should I make a DateTimeField model and abandon DateFields? What are the best practices here?

+6
source share
2 answers

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

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

Returns a knowing date-time that represents the same point in time as the value in the time zone, the value is 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
source

The @kalo answer didn't work for me, so I created this utility function from what ultimately worked for me based on its 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 00:00 eliminated the following errors :

  • Object 'datetime.date' does not have attribute 'tzinfo'
  • The str object does not have the tzinfo attribute
0
source

Source: https://habr.com/ru/post/988683/


All Articles