using django 1.4 I have a model with a datetimefield. I imported django.utils.timezone to use as the default value.
from django.utils import timezone
date = models.DateTimeField(default=timezone.now)
however I still receive the warning about DateTimeField received naive date.
i have set USE_TZ to true so it should be returning aware datetimes
djangos putting in a default date value that isn't tz aware because the field isnt nullable by default. setting null to true means it will just set the date to to NULL instead so the warning isnt raised:
date = models.DateTimeField(default=timezone.now, null=True)
In my case, I kept receiving the issue when I ran tests. This is because of a past migration that incorrectly used datetime instead of timezone. I reverted back to the migration before the one causing the warning, deleted it, ran makemigrations again. This solved the issue for me.
now()
Returns an aware or naive datetime that represents the current
point in time when USE_TZ is True or False respectively.
https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.timezone.now
I know this is side-stepping the issue but have you tried auto_now_add=True on your field instead? No need to use default for what you want.
On the other hand your version should work as well if you have indeed USE_TZ=True.
I'd say it does work, and you get the RunTimeWarning from somewhere where you set the date field directly instead and not from the default. Try to narrow down when is the warning triggered more exactly.
Related
English is the default language of the project. When I switch language, values of all date fields are disrepair. When I try to fill up the form and send it, appear this error: RuntimeWarning: DateTimeField received a naive datetime (2022-11-27 12:00:00.045143) while time zone support is active.
I think the problem with time zone. if make this USE_TZ = False the translation is not working at all...
I'm trying to set the default value for a Date field to a future date with respect to today. However, it gives me the following warning when I set it as below.
return_date = models.DateField(default=(timezone.now() + timedelta(days=1)))
booking.Booking.return_date: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for
this field. This may not be what you want. If you want to have the
current date as default, use `django.utils.timezone.now`
Same warning with the following code.
return_date = models.DateField(default=(date.today() + timedelta(days=1)))
What is the correct way to do this?
Thanks.
You are giving it a fixed time(cause you are calling the timezone.now() so its returned value will be the default) you should pass the function to the default without calling it, like this
def return_date_time():
now = timezone.now()
return now + timedelta(days=1)
and in your field:
return_date = models.DateField(default=return_date_time)
### dont call it, so it will be evaluated by djanog when creating an instance
Try using datetime.date instead of adding to timezone.now
Here is an excerpt from django docs
DateField
class DateField(auto_now=False, auto_now_add=False, **options)
A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:
DateField.auto_now
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.
DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:
For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()
The default form widget for this field is a TextInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key.
The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.
I have deleted all timezone-naive entries out of my Sqlite-DB. So now they remaining entries have a datefield like this:
2016-09-04 13:28:16+00
When I now run my query like this:
result = Feedentry.objects.filter(date_published__gt=timezone('Europe/Berlin').localize(datetime(2016, 8, 31, 17)))
First I receive no error, but as soon as I want to access the result (or len(result)) I receive the following error:
raise ValueError('Not naive datetime (tzinfo is already set)')
Any ideas how to solve it or what I did wrong?
Django always stores datetimes in UTC. And in SQLite it doesn't store any timezone information at all:
[Databases other than PostgreSQL] store datetimes without time zone information. If you switch from USE_TZ = False to USE_TZ = True, you must convert your data from local time to UTC – which isn’t deterministic if your local time has DST.
So first you need to go through your database and convert all the values to UTC; otherwise, Django will not interpret the values correctly.
As for your comparison, it is correct if you're using pytz.timezone and a naive datetime. But the error message implies that whatever datetime you're passing to localize() is already timezone-aware. To convert a timezone-aware datetime you need to use datetime.astimezone(), as noted in the pytz documentation.
I have :
TIME_ZONE = 'Europe/Paris'
USE_L10N = True
USE_TZ = True
in my settings.py file. I am living in Istanbul/Turkey and there is one hour difference between Paris and Istanbul.
In the admin side when selecting a date, django correctly shows 1 hour difference. And using template tag i am getting the datetime i have set in the admin.
But when i pass the datetime via python using beginning_date.strftime("%H:%M") python substracts 1 hour from the value that was set via admin which is not true.
How can i solve this?
Use the Django template defaultfilters to format your dates in Python code.
from django.template.defaultfilters import date as _date
_date(datetime_object, "%H:%M")
And, maybe related: Django cannot reliably use alternate time zones in a Windows. See documentation.
I don't think Turkey has anything to do with it.
My guess is that the one-hour difference you're seeing is between the Paris timezone—which is being used, by default, to interpret and display dates—and UTC—which is being used to store the datetime, and which is the timezone of the datetime returned from the database.
If that's correct, then you can just use django.utils.timezone.localtime to convert the datetime to the current time zone (which by default will be TIME_ZONE):
localtime(beginning_date).strftime("%H:%M")
The timezone for my users is fixed to PST.
I can't make timezone.now() output the correct time. In settings.py I have the timezone set to US/Pacific and USE_TZ=False. Am I doing something wrong? The timezone.now() is 9 hours ahead.
Also, if I want to adjust the timezones some time later, is there a nice way to do it? Django's documentation seems kinda messy in this regard.
USE_TZ = False tells django to ignore timezone information. Switch it to USE_TZ = True and you should be fine.
With this in place, changing timezones in future should be as simple as updating the timezone setting as the timezone is saved with the date when USE_TZ = True
You should really have USE_TZ=True and the timezone set to US/Pacific. Then all the dates will be stored as UTC and converted to PDT on the front-end. This makes it easier if/when you have to change timezones later since all of the datetimes are stored as UTC rather than a naive PDT.