Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warning when creating a Source with default due_poll value #9

Open
philgyford opened this issue Oct 4, 2022 · 3 comments
Open

Warning when creating a Source with default due_poll value #9

philgyford opened this issue Oct 4, 2022 · 3 comments

Comments

@philgyford
Copy link
Contributor

If I have USE_TZ = True in my settings, and I create a new Source without setting its due_poll field:

source = Source.objects.create(feed_url="https://example.com/feed")

Then I get this warning:

/usr/local/lib/python3.10/site-packages/django/db/models/fields/__init__.py:1564: RuntimeWarning: DateTimeField Source.due_poll received a naive datetime (1900-01-01 00:00:00) while time zone support is active.
  warnings.warn(

Because the default value is set like this:

    due_poll      = models.DateTimeField(default=datetime.datetime(1900, 1, 1))

I'm not sure off the top of my head the best way to fix this, taking into account the value of USE_TZ and which version of Django is currently used, given the change from pytz to zoneinfo (available in python from 3.9) that happened with Django 4.0. e.g. https://stackoverflow.com/a/71823301/250962

And, fwiw, timezone support will be enabled by default with Django 5.0.

@philgyford
Copy link
Contributor Author

I tried doing this to add a timezone:

from django.utils.timezone import make_aware

    due_poll      = models.DateTimeField(default=make_aware(datetime.datetime(1900, 1, 1)))

In the resulting migration it comes out as :

        migrations.AlterField(
            model_name='source',
            name='due_poll',
            field=models.DateTimeField(
                default=datetime.datetime(1900, 1, 1, 5, 0, tzinfo=datetime.timezone.utc)
            ),
        ),

The odd thing is, it sets the timezone to UTC regardless of whether my project has USE_TZ set to True or False, and even if I have USE_TZ = True and TIME_ZONE = 'America/New_York'.

Maybe that's fine? I'm not sure. I guess, given it's over a century ago, it's not that important which timezone it's in :)

Happy to add a pull request for this too - let me know.

@xurble
Copy link
Owner

xurble commented Nov 4, 2022

There's a way to do this using a callable generator as the default value. I'll dig it out from another project I've used it on.

@xurble
Copy link
Owner

xurble commented Nov 4, 2022

Although, actually your way is just fine too 🤷‍♂️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants