GithubHelp home page GithubHelp logo

mfogel / django-timezone-field Goto Github PK

View Code? Open in Web Editor NEW
381.0 381.0 98.0 435 KB

A Django app providing DB, form, and REST framework fields for zoneinfo and pytz timezone objects.

License: BSD 2-Clause "Simplified" License

Python 100.00%
django python timezones

django-timezone-field's People

Contributors

apenwarr avatar azzy avatar benjaminrigaud avatar brosner avatar cclauss avatar dougn avatar eukreign avatar hrbonz avatar jameschristopher avatar jeremystretch avatar jezdez avatar jtauber avatar justin-f-perez avatar kevin-brown avatar knobix avatar medmunds avatar mfogel avatar mpdaugherty avatar siecje avatar sm-m-1 avatar thijstriemstra avatar tim-schilling avatar tkhyn avatar zemanel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-timezone-field's Issues

Can't create migrations in Django 1.7

When trying to create a migration in Django 1.7, I get—

ValueError: Cannot serialize: <DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing

Taking some inspiration from #7 I've replaced the DstTzInfo instances with the timezone names, and it seems to work fine, but it's a stopgap.

null=True should be enforced

Hi,

Though the comments in the code state that the empty value is '' (the empty string) even if the field is set to None (null), this is not true. The opposite is true: the empty value is always encoded as None. (See lines 86-87.)

However, by default the field (as the underlying CharField) has null=False and it will break things as soon as one adds an empty field. (E.g. right when running the migration.)

Django 1.11 and Python 3.6 causes error in migration

We recently upgraded to django 1.11 and python 3.6. This caused a migration that should have ran without any problem. However, due to django's field internals keeping values as bytes rather than unicode this errors out in _get_python_and_db_repr as there is no handler for a bytes type.

Stacktrace from migration:

 File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/project/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/project/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/project/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/project/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/project/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/project/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/project/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/project/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/project/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 215, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/project/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 513, in alter_field
    old_db_params, new_db_params, strict)
  File "/project/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
    new_db_params, strict,
  File "/project/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 602, in _alter_field
    old_default = self.effective_default(old_field)
  File "/project/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 206, in effective_default
    default = field.get_default()
  File "/project/lib/python3.6/site-packages/timezone_field/fields.py", line 92, in get_default
    return self._get_python_and_db_repr(value)[0]
  File "/project/lib/python3.6/site-packages/timezone_field/fields.py", line 118, in _get_python_and_db_repr
    raise ValidationError("Invalid timezone '%s'" % value)
django.core.exceptions.ValidationError: ["Invalid timezone 'b'UTC''"]

PR to follow.

Django 3.0 support

It seems that this package causes a crash with Django 3.0

Upon running the runserver command, I get:

File "/donnees/virtualenvs/django/lib/python3.8/site-packages/timezone_field/fields.py", line 5, in <module>
    from django.utils import six
ImportError: cannot import name 'six' from 'django.utils'

License

What license is this released under? Can it be added to the project as well?

Strange Offsets

I have a model...

from timezone_field import TimeZoneField
class User(AbstractUser):
    email = models.EmailField(unique=True)
    timezone = TimeZoneField(default="UTC")

I go to save a user instance...

user = User.objects.create(
 username="jo", email="[email protected]", timezone="Pacific/Auckland"
)
user.set_password("password")
user.full_clean()
user.save()

Then, in a new shell I examine the saved user...

>>> user = User.objects.first()
>>> user
<User: jo>
>>> user.timezone
<DstTzInfo 'Pacific/Auckland' LMT+11:39:00 STD>

Why is the timezone offset by 11 hours and 39 minutes? And why is it using Local Mean Time?

This bizarre behaviour is seen when accessing instances through the shell, and when running functional tests, but for some reason not in the live website itself. The website behaves as expected, but in tests this strange offset is seen, which makes them fail.

Other timezones all have arbitrary minute offsets too - Europe/London is 2 minutes for example.

I'm new to handling timezones so maybe I've missed something obvious, but I am very confused by this!

I am writing in the Europe/London timezone, and TIME_ZONE = "UTC" in settings.py.

Python 3.6, Django 2.0, timezone_field 2.1 (I know tzf 2.1 doesn't officially support django 2.0, but I wouldn't have thought that would cause something like this?)

Wheel support

http://pythonwheels.com/

Right now, only the tar.gz file is being distributed on PyPI for django-timezone-field, which isn't that much of an issue, but it does add some time to installing the package.

This package should be compatible with the Wheel format, considering it doesn't appear to have any C dependencies and it is compatible with both Python 2 and 3. As a result, you should only need to generate a universal wheel and then everyone (on all systems) will get the ability to install django-timezone-field with just the wheel, without having to do any extra work.

Incorrect null=False behavior

Because of the change in 71f107e, you can set a TimeZoneField to None and save the model without raising an IntegrityError. This is because get_prep_value() returns the empty string ('').

This behavior is inconsistent with other null=False fields, and there is no longer any way for me to enforce that my model must have a time zone.

Please support django 1.7

Hello,

The documentation has not mentioned about support for 1.7 django version. Is 1.7 fully supported ? Or there are some bugs to be solved ?

5.0 - No time zone found with key Pacific/Kanto

Hi, I just upgraded to django-timezone-field 5.0 and have the migrations failing on DB + Tables creation
Django : 4.0.2
Python : 3.10.0
Using official 3.10-slim-bullseye docker image
Model code :

class UserProfile(Model):

    user = OneToOneField(
        User,
        on_delete=CASCADE,
        related_name="profile",
        verbose_name=_("Utilisateur"),
    )
    timezone = TimeZoneField(
        _("Fuseau horaire"),
        default="Europe/Paris",
        choices_display="WITH_GMT_OFFSET",
    )

Traceback :

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/zoneinfo/_common.py", line 12, in load_tzdata
    return importlib.resources.open_binary(package_name, resource_name)
  File "/usr/local/lib/python3.10/importlib/resources.py", line 43, in open_binary
    package = _common.get_package(package)
  File "/usr/local/lib/python3.10/importlib/_common.py", line 66, in get_package
    resolved = resolve(package)
  File "/usr/local/lib/python3.10/importlib/_common.py", line 57, in resolve
    return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand)
  File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tzdata'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/app/manage.py", line 31, in <module>
    execute_from_command_line(sys.argv)
  File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute
    django.setup()
  File "/opt/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/opt/venv/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/opt/venv/lib/python3.10/site-packages/django/apps/config.py", line 300, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/opt/app/nova/users/models.py", line 19, in <module>
    from timezone_field import TimeZoneField
  File "/opt/venv/lib/python3.10/site-packages/timezone_field/__init__.py", line 1, in <module>
    from timezone_field.fields import TimeZoneField
  File "/opt/venv/lib/python3.10/site-packages/timezone_field/fields.py", line 11, in <module>
    class TimeZoneField(models.Field):
  File "/opt/venv/lib/python3.10/site-packages/timezone_field/fields.py", line 41, in TimeZoneField
    default_zoneinfo_tzs = [ZoneInfo(tz) for tz in pytz.common_timezones]
  File "/opt/venv/lib/python3.10/site-packages/timezone_field/fields.py", line 41, in <listcomp>
    default_zoneinfo_tzs = [ZoneInfo(tz) for tz in pytz.common_timezones]
  File "/usr/local/lib/python3.10/zoneinfo/_common.py", line 24, in load_tzdata
    raise ZoneInfoNotFoundError(f"No time zone found with key {key}")
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Pacific/Kanton'

Cannot install from sdist

Attempting to install the latest version with current pip from sdist leads to the following error:

$ pip install --no-binary=:all: django-timezone-field==4.2.1 -vvv
[…]
Collecting django-timezone-field==4.2.1
  Created temporary directory: /tmp/pip-unpack-rn_pkd07
  Looking up "https://files.pythonhosted.org/packages/19/0c/92d0666a4372390284919080f49306986e29614756ff48b63b9bb6690c19/django-timezone-field-4.2.1.tar.gz" in the cache
  Current age based on date: 1611
  Ignoring unknown cache-control directive: immutable
  Freshness lifetime from max-age: 365000000
  The response is "fresh", returning cached response
  365000000 > 1611
  Using cached django-timezone-field-4.2.1.tar.gz (8.9 kB)
  Added django-timezone-field==4.2.1 from https://files.pythonhosted.org/packages/19/0c/92d0666a4372390284919080f49306986e29614756ff48b63b9bb6690c19/django-timezone-field-4.2.1.tar.gz#sha256=97780cde658daa5094ae515bb55ca97c1352928ab554041207ad515dee3fe971 to build tracker '/tmp/pip-req-tracker-4rf2zvm7'
  Created temporary directory: /tmp/pip-build-env-q8z2wvtb
  Created temporary directory: /tmp/pip-standalone-pip-200_p119
  Running command /usr/local/bin/python /tmp/pip-standalone-pip-200_p119/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-q8z2wvtb/overlay --no-warn-script-location -v --no-binary :all: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0'
  Using pip 21.2.4 from /tmp/pip-standalone-pip-200_p119/__env_pip__.zip/pip (python 3.8)
  Collecting poetry-core>=1.0.0
    Using cached poetry-core-1.0.7.tar.gz (346 kB)
    Getting requirements to build wheel: started
    Running command /usr/local/bin/python /tmp/tmpwupyjzgw get_requires_for_build_wheel /tmp/tmphxw7_q4a
    Getting requirements to build wheel: finished with status 'done'
      Preparing wheel metadata: started
      Running command /usr/local/bin/python /tmp/tmp6hhp3xnj prepare_metadata_for_build_wheel /tmp/tmptnr_0jsy
      Preparing wheel metadata: finished with status 'done'
  Building wheels for collected packages: poetry-core
    Building wheel for poetry-core (PEP 517): started
    Running command /usr/local/bin/python /tmp/tmp3hwc6xt8 build_wheel /tmp/tmp277z43ii
    Building wheel for poetry-core (PEP 517): finished with status 'done'
    Created wheel for poetry-core: filename=poetry_core-1.0.7-py2.py3-none-any.whl size=424762 sha256=e49b8e329c8973f0b88641ca0c96e61eb949c997c26a06113ba3c49ae50e8a2d
    Stored in directory: /root/.cache/pip/wheels/ba/e4/44/ea31b9805c00435905446469f726699e1c272aa5339fbe35a5
  Successfully built poetry-core
  Installing collected packages: poetry-core
  Successfully installed poetry-core-1.0.7
  WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
  WARNING: You are using pip version 21.2.4; however, version 21.3 is available.
  You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
  Installing build dependencies ... done
  Running command /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py get_requires_for_build_wheel /tmp/tmpdl98aurd
  Getting requirements to build wheel ... done
    Created temporary directory: /tmp/pip-modern-metadata-dw2y8eoa
    Running command /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py prepare_metadata_for_build_wheel /tmp/tmp1qbs2q9f
    Traceback (most recent call last):
      File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 349, in <module>
        main()
      File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 331, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 151, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "/tmp/pip-build-env-q8z2wvtb/overlay/lib/python3.8/site-packages/poetry/core/masonry/api.py", line 44, in prepare_metadata_for_build_wheel
        builder = WheelBuilder(poetry)
      File "/tmp/pip-build-env-q8z2wvtb/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/wheel.py", line 57, in __init__
        super(WheelBuilder, self).__init__(poetry, executable=executable)
      File "/tmp/pip-build-env-q8z2wvtb/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/builder.py", line 85, in __init__
        self._module = Module(
      File "/tmp/pip-build-env-q8z2wvtb/overlay/lib/python3.8/site-packages/poetry/core/masonry/utils/module.py", line 63, in __init__
        raise ModuleOrPackageNotFound(
    poetry.core.masonry.utils.module.ModuleOrPackageNotFound: No file/folder found for package django-timezone-field
    Preparing wheel metadata ... error

According to the docs for poetry, since the Python package name does not match the pypi name, it needs to be customized with

packages = [
    { include = "timezone_field" },
]

in the [tool.poetry] section of pyproject.toml.

However, I don't have enough experience with poetry to know whether this is enough to pull in all the required files that you expect to have in wheels, or not.

SubfieldBase has been deprecated in Django 1.8

The TimeZoneField class uses models.SubfieldBase which is deprecated in Django 1.8 and will be removed in 1.10.

Django documentation reference is https://docs.djangoproject.com/en/1.8/releases/1.8/#subfieldbase

The use appears in timezone_field/fields.py", line 100

Discovered this in the process of upgrading to Django 1.8 as I run tests with PendingDeprecationWarning converted to errors.

I'm not familiar with this aspect of Django so haven't proposed a pull request.

Atul

How to set Default Timezone in the form

How do you set default timezone to the form which I have done like this:

timezone = TimeZoneFormField(choices_display='WITH_GMT_OFFSET', default='UTC', required=True)

I get this error>
TypeError: init() got an unexpected keyword argument 'default'

Breaking Changes in 3+

We are in the process of catching up our code base and are migrating from v1.3 to v3.1. In the process of this, we realized that previously v1.3 was already returning the object. However, in v3.1 it is now always return the string. We used ipdb to verify that get_prep_value() is always being called, and that's the reason the string is returning.

If it helps, here is our theory.

In v1.3, choices was a named parameter. If it was not provided by the user, it simply used the default choices from your library, https://github.com/mfogel/django-timezone-field/blob/1.3/timezone_field/fields.py#L42-L43. This was good for our use case because the default format of (obj, txt) was always sufficient for us.

However, when you released v3.1, we realized that you changed the code to remove the choices parameter as named. Instead, it's a kwargs, and if not present it injects the default choices from your library into kwargs['choices']. And this is where the problem occurs.

In the deconstruct function, you check if "choices" exists inside of kwargs. Previously, it would not have existed (ever) and therefore it would have allowed the object to return using to_python. Instead, this check if (https://github.com/mfogel/django-timezone-field/blob/3.1/timezone_field/fields.py#L91-L92) is now true, and it is always returning the string representation.

Again, we're not sure we fully understand everything with the change from models.SubfieldBase, but this is what we think might be happening.

[feature request] `verbase_name` support

I am a big fan of consistency and currently all my model fields have an explicit translated verbase_name property.

Example:

    timezone = TimeZoneField(
        verbase_name=_('timezone'),
        default=pytz.UTC,
    )

However this currently does not work for TimeZoneField. :|
I get this Error: __init__() got an unexpected keyword argument 'verbase_name'

How about adding support for it? :)

Paginate or load zones over ajax

Right now the template function naively loads every timezone as options in form. I would be nice to load these over ajax to speed up delivery of the webpage.

stdlib zoneinfo support

Have you considered adding support for https://docs.python.org/3.9/library/zoneinfo.html in some way?

There are tree approaches that come to mind.

  1. Replace all of pytz with zoneinfo equivalents (optionally installing the backports.zoneinfo module).
  2. Add support for zoneinfo alongside pytz, allowing ZoneInfo as field values. Adding a use_pytz as a new parameter on TimeZoneField, defaulting to False which would start returning ZoneInfo objects from db instead of pytz ones. Deprecating pytz support.
  3. Support for pytz and zoneinfo equally with use_pytz parameter defaulting to True. Not deprecating pytz.

Thanks for a great package btw, keep up the good work!

NonExistentTimeError thrown during DST transition

Here is my model field, I need to show all the obsolete timezones as the frontend clients still send the timezone in obsolete formats(Asia/Calcutta instead of Asia/Kokatta). Not sure if that's the reason.

TIMEZONE_CHOICES = [(pytz.timezone(tz), tz) for tz in pytz.all_timezones]

timezone = TimeZoneField(choices_display='WITH_GMT_OFFSET', choices=TIMEZONE_CHOICES, blank=True, null=True)

Error

timezone = TimeZoneField(choices_display='WITH_GMT_OFFSET', choices=TIMEZONE_CHOICES, blank=True, null=True)
  File "timezone_field/fields.py", line 72, in __init__
    choices = with_gmt_offset(values)
  File "timezone_field/choices.py", line 32, in with_gmt_offset
    delta = pytz.timezone(tz_str).utcoffset(now)
  File "pytz/tzinfo.py", line 422, in utcoffset
    dt = self.localize(dt, is_dst)
  File "pytz/tzinfo.py", line 341, in localize
    raise NonExistentTimeError(dt)

Sentry error stack

Raise exception on init

I do have TimeZoneField(choices_display='WITH_GMT_OFFSET') field.
At some datetimes it breaks on init with raising pytz.exceptions.NonExistentTimeError.
Date time instance that deliver to exception:
2021-03-22 00:20:50.024855 (between 12am - 1am)
2021-03-26 00:21:06.720454 (between 12am - 1am)
2021-03-26 00:10:51.758070 (between 2am - 3am) - this one raise exception on Asia/Amman tz
To reproduce this you can run manually next code:

import pytz
from datetime import datetime
buggy_time = datetime.fromisoformat('2021-03-26 00:10:51.758070')
timezones = [pytz.timezone(tz) for tz in pytz.common_timezones]  # from TimeZoneField source code
for tz in timezones:
    pytz.timezone(str(tz)).utcoffset(buggy_time)  # this one will raise exception

Here is a code part that raise exception.

Timezone field value always displays as (None) in admin list view

Hi,

When I use this field in a model and set the field to be displayed in the django admin list view, no matter what the value of the field is for any record the value is always displayed as (None). The field is displayed correctly in the edit view for individual records. I tried to create a workaround and I could get the field to display in the list view by creating a method in the model that returns that field, however it feels like this should be done automatically. This is in Django 1.8 with Django Suit theme.

Unexpected keyword argument 'display_GMT_offset'

The README has the following:

timezone2 = TimeZoneFormField(display_GMT_offset=True) # displays like "GMT-08:00 America/Los_Angeles"

But display_GMT_offset does not appear to be a valid argument of TimeZoneFormField. It is only defined under the model class of TimeZoneField.

Is there a way another way we can get our form field to show the GMT offset like "GMT-08:00 America/Los_Angeles" ?

fields.py __init__ missing choices_display argument?

Hello i tried to add choices_display to TimezoneField() but seems like it doesn't accept that argument:

from timezone_field import TimeZoneField

timezone = TimeZoneField(default='Asia/Saigon', choices_display='WITH_GMT_OFFSET')

my environment:

  • MacOS

  • python3.8

  • django-timezone-field version: django-timezone-field = "^4.0"

Full error traceback:

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/core/management/init.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/init.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "/Users/admin/Documents/git/icts/vietphil.hoola/backend/models/init.py", line 1, in
from .user import User
File "/Users/admin/Documents/git/icts/vietphil.hoola/backend/models/user.py", line 7, in
class User(AbstractUser):
File "/Users/admin/Documents/git/icts/vietphil.hoola/backend/models/user.py", line 29, in User
timezone = TimeZoneField(default='Asia/Saigon', choices_display='WITH_GMT_OFFSET')
File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/timezone_field/fields.py", line 74, in init
super(TimeZoneField, self).init(*args, **kwargs)
TypeError: init() got an unexpected keyword argument 'choices_display'

I read over https://github.com/mfogel/django-timezone-field/blob/master/timezone_field/fields.py#L43 and seems like it's correct because you using kwargs. Do you know why extra argument caused the error?

choices_display='WITH_GMT_OFFSET' kwarg causes django migrations to generate many AlterField() statements

Thanks for this project! Since upgrading to 4.1.1 earlier this year, every time I do makemigrations for other aspects of my project, an existing timezone field gets a migration too - so I have 5 AlterField operations that are all the same. Any idea what the cause of this would be or how to resolve?

operations = [
        migrations.AlterField(
            model_name='some_model_name',
            name='timezone',
            field=timezone_field.fields.TimeZoneField(choices=[('Pacific/Midway', 'GMT-11:00 Pacific/Midway'), ('Pacific/Niue', 'GMT-11:00 Pacific/Niue'), ('Pacific/Pago_Pago', 'GMT-11:00 Pacific/Pago Pago'), ('Pacific/Honolulu', 'GMT-10:00 Pacific/Honolulu'), ('Pacific/Rarotonga', 'GMT-10:00 Pacific/Rarotonga'), ('Pacific/Tahiti', 'GMT-10:00 Pacific/Tahiti'), ('US/Hawaii', 'GMT-10:00 US/Hawaii'), ('Pacific/Marquesas', 'GMT-09:30 Pacific/Marquesas'), ('America/Adak', 'GMT-09:00 America/Adak'), ('Pacific/Gambier', 'GMT-09:00 Pacific/Gambier'), ('America/Anchorage', 'GMT-08:00 America/Anchorage'), ('America/Juneau', 'GMT-08:00 America/Juneau'), ('America/Metlakatla', 'GMT-08:00 America/Metlakatla'), ('America/Nome', 'GMT-08:00 America/Nome'), ('America/Sitka', 'GMT-08:00 America/Sitka'), ('America/Yakutat', 'GMT-08:00 America/Yakutat'), ('Pacific/Pitcairn', 'GMT-08:00 Pacific/Pitcairn'), ('US/Alaska', 'GMT-08:00 US/Alaska'), ('America/Creston', 'GMT-07:00 America/Creston'), ('America/Dawson', 'GMT-07:00 America/Dawson'), ('America/Dawson_Creek', 'GMT-07:00 America/Dawson Creek'), ('America/Fort_Nelson', 'GMT-07:00 America/Fort Nelson'), ('America/Hermosillo', 'GMT-07:00 America/Hermosillo'), ('America/Los_Angeles', 'GMT-07:00 America/Los Angeles'), ('America/Phoenix', 'GMT-07:00 America/Phoenix'), ('America/Tijuana', 'GMT-07:00 America/Tijuana'), ('America/Vancouver', 'GMT-07:00 America/Vancouver'), ('America/Whitehorse', 'GMT-07:00 America/Whitehorse'), ('Canada/Pacific', 'GMT-07:00 Canada/Pacific'), ('US/Arizona', 'GMT-07:00 US/Arizona'), ('US/Pacific', 'GMT-07:00 US/Pacific'), ('America/Belize', 'GMT-06:00 America/Belize'), ('America/Boise', 'GMT-06:00 America/Boise'), ('America/Cambridge_Bay', 'GMT-06:00 America/Cambridge Bay'), ('America/Chihuahua', 'GMT-06:00 America/Chihuahua'), ('America/Costa_Rica', 'GMT-06:00 America/Costa Rica'), ('America/Denver', 'GMT-06:00 America/Denver'), ('America/Edmonton', 'GMT-06:00 America/Edmonton'), ('America/El_Salvador', 'GMT-06:00 America/El Salvador'), ('America/Guatemala', 'GMT-06:00 America/Guatemala'), ('America/Inuvik', 'GMT-06:00 America/Inuvik'), ('America/Managua', 'GMT-06:00 America/Managua'), ('America/Mazatlan', 'GMT-06:00 America/Mazatlan'), ('America/Ojinaga', 'GMT-06:00 America/Ojinaga'), ('America/Regina', 'GMT-06:00 America/Regina'), ('America/Swift_Current', 'GMT-06:00 America/Swift Current'), ('America/Tegucigalpa', 'GMT-06:00 America/Tegucigalpa'), ('America/Yellowknife', 'GMT-06:00 America/Yellowknife'), ('Canada/Mountain', 'GMT-06:00 Canada/Mountain'), ('Pacific/Galapagos', 'GMT-06:00 Pacific/Galapagos'), ('US/Mountain', 'GMT-06:00 US/Mountain'), ('America/Atikokan', 'GMT-05:00 America/Atikokan'), ('America/Bahia_Banderas', 'GMT-05:00 America/Bahia Banderas'), ('America/Bogota', 'GMT-05:00 America/Bogota'), ('America/Cancun', 'GMT-05:00 America/Cancun'), ('America/Cayman', 'GMT-05:00 America/Cayman'), ('America/Chicago', 'GMT-05:00 America/Chicago'), ('America/Eirunepe', 'GMT-05:00 America/Eirunepe'), ('America/Guayaquil', 'GMT-05:00 America/Guayaquil'), ('America/Indiana/Knox', 'GMT-05:00 America/Indiana/Knox'), ('America/Indiana/Tell_City', 'GMT-05:00 America/Indiana/Tell City'), ('America/Jamaica', 'GMT-05:00 America/Jamaica'), ('America/Lima', 'GMT-05:00 America/Lima'), ('America/Matamoros', 'GMT-05:00 America/Matamoros'), ('America/Menominee', 'GMT-05:00 America/Menominee'), ('America/Merida', 'GMT-05:00 America/Merida'), ('America/Mexico_City', 'GMT-05:00 America/Mexico City'), ('America/Monterrey', 'GMT-05:00 America/Monterrey'), ('America/North_Dakota/Beulah', 'GMT-05:00 America/North Dakota/Beulah'), ('America/North_Dakota/Center', 'GMT-05:00 America/North Dakota/Center'), ('America/North_Dakota/New_Salem', 'GMT-05:00 America/North Dakota/New Salem'), ('America/Panama', 'GMT-05:00 America/Panama'), ('America/Rainy_River', 'GMT-05:00 America/Rainy River'), ('America/Rankin_Inlet', 'GMT-05:00 America/Rankin Inlet'), ('America/Resolute', 'GMT-05:00 America/Resolute'), ('America/Rio_Branco', 'GMT-05:00 America/Rio Branco'), ('America/Winnipeg', 'GMT-05:00 America/Winnipeg'), ('Canada/Central', 'GMT-05:00 Canada/Central'), ('Pacific/Easter', 'GMT-05:00 Pacific/Easter'), ('US/Central', 'GMT-05:00 US/Central'), ('America/Anguilla', 'GMT-04:00 America/Anguilla'), ('America/Antigua', 'GMT-04:00 America/Antigua'), ('America/Aruba', 'GMT-04:00 America/Aruba'), ('America/Asuncion', 'GMT-04:00 America/Asuncion'), ('America/Barbados', 'GMT-04:00 America/Barbados'), ('America/Blanc-Sablon', 'GMT-04:00 America/Blanc-Sablon'), ('America/Boa_Vista', 'GMT-04:00 America/Boa Vista'), ('America/Campo_Grande', 'GMT-04:00 America/Campo Grande'), ('America/Caracas', 'GMT-04:00 America/Caracas'), ('America/Cuiaba', 'GMT-04:00 America/Cuiaba'), ('America/Curacao', 'GMT-04:00 America/Curacao'), ('America/Detroit', 'GMT-04:00 America/Detroit'), ('America/Dominica', 'GMT-04:00 America/Dominica'), ('America/Grand_Turk', 'GMT-04:00 America/Grand Turk'), ('America/Grenada', 'GMT-04:00 America/Grenada'), ('America/Guadeloupe', 'GMT-04:00 America/Guadeloupe'), ('America/Guyana', 'GMT-04:00 America/Guyana'), ('America/Havana', 'GMT-04:00 America/Havana'), ('America/Indiana/Indianapolis', 'GMT-04:00 America/Indiana/Indianapolis'), ('America/Indiana/Marengo', 'GMT-04:00 America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'GMT-04:00 America/Indiana/Petersburg'), ('America/Indiana/Vevay', 'GMT-04:00 America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'GMT-04:00 America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'GMT-04:00 America/Indiana/Winamac'), ('America/Iqaluit', 'GMT-04:00 America/Iqaluit'), ('America/Kentucky/Louisville', 'GMT-04:00 America/Kentucky/Louisville'), ('America/Kentucky/Monticello', 'GMT-04:00 America/Kentucky/Monticello'), ('America/Kralendijk', 'GMT-04:00 America/Kralendijk'), ('America/La_Paz', 'GMT-04:00 America/La Paz'), ('America/Lower_Princes', 'GMT-04:00 America/Lower Princes'), ('America/Manaus', 'GMT-04:00 America/Manaus'), ('America/Marigot', 'GMT-04:00 America/Marigot'), ('America/Martinique', 'GMT-04:00 America/Martinique'), ('America/Montserrat', 'GMT-04:00 America/Montserrat'), ('America/Nassau', 'GMT-04:00 America/Nassau'), ('America/New_York', 'GMT-04:00 America/New York'), ('America/Nipigon', 'GMT-04:00 America/Nipigon'), ('America/Pangnirtung', 'GMT-04:00 America/Pangnirtung'), ('America/Port-au-Prince', 'GMT-04:00 America/Port-au-Prince'), ('America/Port_of_Spain', 'GMT-04:00 America/Port of Spain'), ('America/Porto_Velho', 'GMT-04:00 America/Porto Velho'), ('America/Puerto_Rico', 'GMT-04:00 America/Puerto Rico'), ('America/Santo_Domingo', 'GMT-04:00 America/Santo Domingo'), ('America/St_Barthelemy', 'GMT-04:00 America/St Barthelemy'), ('America/St_Kitts', 'GMT-04:00 America/St Kitts'), ('America/St_Lucia', 'GMT-04:00 America/St Lucia'), ('America/St_Thomas', 'GMT-04:00 America/St Thomas'), ('America/St_Vincent', 'GMT-04:00 America/St Vincent'), ('America/Thunder_Bay', 'GMT-04:00 America/Thunder Bay'), ('America/Toronto', 'GMT-04:00 America/Toronto'), ('America/Tortola', 'GMT-04:00 America/Tortola'), ('Canada/Eastern', 'GMT-04:00 Canada/Eastern'), ('US/Eastern', 'GMT-04:00 US/Eastern'), ('America/Araguaina', 'GMT-03:00 America/Araguaina'), ('America/Argentina/Buenos_Aires', 'GMT-03:00 America/Argentina/Buenos Aires'), ('America/Argentina/Catamarca', 'GMT-03:00 America/Argentina/Catamarca'), ('America/Argentina/Cordoba', 'GMT-03:00 America/Argentina/Cordoba'), ('America/Argentina/Jujuy', 'GMT-03:00 America/Argentina/Jujuy'), ('America/Argentina/La_Rioja', 'GMT-03:00 America/Argentina/La Rioja'), ('America/Argentina/Mendoza', 'GMT-03:00 America/Argentina/Mendoza'), ('America/Argentina/Rio_Gallegos', 'GMT-03:00 America/Argentina/Rio Gallegos'), ('America/Argentina/Salta', 'GMT-03:00 America/Argentina/Salta'), ('America/Argentina/San_Juan', 'GMT-03:00 America/Argentina/San Juan'), ('America/Argentina/San_Luis', 'GMT-03:00 America/Argentina/San Luis'), ('America/Argentina/Tucuman', 'GMT-03:00 America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'GMT-03:00 America/Argentina/Ushuaia'), ('America/Bahia', 'GMT-03:00 America/Bahia'), ('America/Belem', 'GMT-03:00 America/Belem'), ('America/Cayenne', 'GMT-03:00 America/Cayenne'), ('America/Fortaleza', 'GMT-03:00 America/Fortaleza'), ('America/Glace_Bay', 'GMT-03:00 America/Glace Bay'), ('America/Goose_Bay', 'GMT-03:00 America/Goose Bay'), ('America/Halifax', 'GMT-03:00 America/Halifax'), ('America/Maceio', 'GMT-03:00 America/Maceio'), ('America/Moncton', 'GMT-03:00 America/Moncton'), ('America/Montevideo', 'GMT-03:00 America/Montevideo'), ('America/Paramaribo', 'GMT-03:00 America/Paramaribo'), ('America/Punta_Arenas', 'GMT-03:00 America/Punta Arenas'), ('America/Recife', 'GMT-03:00 America/Recife'), ('America/Santarem', 'GMT-03:00 America/Santarem'), ('America/Santiago', 'GMT-03:00 America/Santiago'), ('America/Sao_Paulo', 'GMT-03:00 America/Sao Paulo'), ('America/Thule', 'GMT-03:00 America/Thule'), ('Antarctica/Palmer', 'GMT-03:00 Antarctica/Palmer'), ('Antarctica/Rothera', 'GMT-03:00 Antarctica/Rothera'), ('Atlantic/Bermuda', 'GMT-03:00 Atlantic/Bermuda'), ('Atlantic/Stanley', 'GMT-03:00 Atlantic/Stanley'), ('Canada/Atlantic', 'GMT-03:00 Canada/Atlantic'), ('America/St_Johns', 'GMT-02:30 America/St Johns'), ('Canada/Newfoundland', 'GMT-02:30 Canada/Newfoundland'), ('America/Godthab', 'GMT-02:00 America/Godthab'), ('America/Miquelon', 'GMT-02:00 America/Miquelon'), ('America/Noronha', 'GMT-02:00 America/Noronha'), ('Atlantic/South_Georgia', 'GMT-02:00 Atlantic/South Georgia'), ('Atlantic/Cape_Verde', 'GMT-01:00 Atlantic/Cape Verde'), ('Africa/Abidjan', 'GMT+00:00 Africa/Abidjan'), ('Africa/Accra', 'GMT+00:00 Africa/Accra'), ('Africa/Bamako', 'GMT+00:00 Africa/Bamako'), ('Africa/Banjul', 'GMT+00:00 Africa/Banjul'), ('Africa/Bissau', 'GMT+00:00 Africa/Bissau'), ('Africa/Casablanca', 'GMT+00:00 Africa/Casablanca'), ('Africa/Conakry', 'GMT+00:00 Africa/Conakry'), ('Africa/Dakar', 'GMT+00:00 Africa/Dakar'), ('Africa/El_Aaiun', 'GMT+00:00 Africa/El Aaiun'), ('Africa/Freetown', 'GMT+00:00 Africa/Freetown'), ('Africa/Lome', 'GMT+00:00 Africa/Lome'), ('Africa/Monrovia', 'GMT+00:00 Africa/Monrovia'), ('Africa/Nouakchott', 'GMT+00:00 Africa/Nouakchott'), ('Africa/Ouagadougou', 'GMT+00:00 Africa/Ouagadougou'), ('America/Danmarkshavn', 'GMT+00:00 America/Danmarkshavn'), ('America/Scoresbysund', 'GMT+00:00 America/Scoresbysund'), ('Atlantic/Azores', 'GMT+00:00 Atlantic/Azores'), ('Atlantic/Reykjavik', 'GMT+00:00 Atlantic/Reykjavik'), ('Atlantic/St_Helena', 'GMT+00:00 Atlantic/St Helena'), ('GMT', 'GMT+00:00 GMT'), ('UTC', 'GMT+00:00 UTC'), ('Africa/Algiers', 'GMT+01:00 Africa/Algiers'), ('Africa/Bangui', 'GMT+01:00 Africa/Bangui'), ('Africa/Brazzaville', 'GMT+01:00 Africa/Brazzaville'), ('Africa/Douala', 'GMT+01:00 Africa/Douala'), ('Africa/Kinshasa', 'GMT+01:00 Africa/Kinshasa'), ('Africa/Lagos', 'GMT+01:00 Africa/Lagos'), ('Africa/Libreville', 'GMT+01:00 Africa/Libreville'), ('Africa/Luanda', 'GMT+01:00 Africa/Luanda'), ('Africa/Malabo', 'GMT+01:00 Africa/Malabo'), ('Africa/Ndjamena', 'GMT+01:00 Africa/Ndjamena'), ('Africa/Niamey', 'GMT+01:00 Africa/Niamey'), ('Africa/Porto-Novo', 'GMT+01:00 Africa/Porto-Novo'), ('Africa/Sao_Tome', 'GMT+01:00 Africa/Sao Tome'), ('Africa/Tunis', 'GMT+01:00 Africa/Tunis'), ('Atlantic/Canary', 'GMT+01:00 Atlantic/Canary'), ('Atlantic/Faroe', 'GMT+01:00 Atlantic/Faroe'), ('Atlantic/Madeira', 'GMT+01:00 Atlantic/Madeira'), ('Europe/Dublin', 'GMT+01:00 Europe/Dublin'), ('Europe/Guernsey', 'GMT+01:00 Europe/Guernsey'), ('Europe/Isle_of_Man', 'GMT+01:00 Europe/Isle of Man'), ('Europe/Jersey', 'GMT+01:00 Europe/Jersey'), ('Europe/Lisbon', 'GMT+01:00 Europe/Lisbon'), ('Europe/London', 'GMT+01:00 Europe/London'), ('Africa/Blantyre', 'GMT+02:00 Africa/Blantyre'), ('Africa/Bujumbura', 'GMT+02:00 Africa/Bujumbura'), ('Africa/Cairo', 'GMT+02:00 Africa/Cairo'), ('Africa/Ceuta', 'GMT+02:00 Africa/Ceuta'), ('Africa/Gaborone', 'GMT+02:00 Africa/Gaborone'), ('Africa/Harare', 'GMT+02:00 Africa/Harare'), ('Africa/Johannesburg', 'GMT+02:00 Africa/Johannesburg'), ('Africa/Khartoum', 'GMT+02:00 Africa/Khartoum'), ('Africa/Kigali', 'GMT+02:00 Africa/Kigali'), ('Africa/Lubumbashi', 'GMT+02:00 Africa/Lubumbashi'), ('Africa/Lusaka', 'GMT+02:00 Africa/Lusaka'), ('Africa/Maputo', 'GMT+02:00 Africa/Maputo'), ('Africa/Maseru', 'GMT+02:00 Africa/Maseru'), ('Africa/Mbabane', 'GMT+02:00 Africa/Mbabane'), ('Africa/Tripoli', 'GMT+02:00 Africa/Tripoli'), ('Africa/Windhoek', 'GMT+02:00 Africa/Windhoek'), ('Antarctica/Troll', 'GMT+02:00 Antarctica/Troll'), ('Arctic/Longyearbyen', 'GMT+02:00 Arctic/Longyearbyen'), ('Europe/Amsterdam', 'GMT+02:00 Europe/Amsterdam'), ('Europe/Andorra', 'GMT+02:00 Europe/Andorra'), ('Europe/Belgrade', 'GMT+02:00 Europe/Belgrade'), ('Europe/Berlin', 'GMT+02:00 Europe/Berlin'), ('Europe/Bratislava', 'GMT+02:00 Europe/Bratislava'), ('Europe/Brussels', 'GMT+02:00 Europe/Brussels'), ('Europe/Budapest', 'GMT+02:00 Europe/Budapest'), ('Europe/Busingen', 'GMT+02:00 Europe/Busingen'), ('Europe/Copenhagen', 'GMT+02:00 Europe/Copenhagen'), ('Europe/Gibraltar', 'GMT+02:00 Europe/Gibraltar'), ('Europe/Kaliningrad', 'GMT+02:00 Europe/Kaliningrad'), ('Europe/Ljubljana', 'GMT+02:00 Europe/Ljubljana'), ('Europe/Luxembourg', 'GMT+02:00 Europe/Luxembourg'), ('Europe/Madrid', 'GMT+02:00 Europe/Madrid'), ('Europe/Malta', 'GMT+02:00 Europe/Malta'), ('Europe/Monaco', 'GMT+02:00 Europe/Monaco'), ('Europe/Oslo', 'GMT+02:00 Europe/Oslo'), ('Europe/Paris', 'GMT+02:00 Europe/Paris'), ('Europe/Podgorica', 'GMT+02:00 Europe/Podgorica'), ('Europe/Prague', 'GMT+02:00 Europe/Prague'), ('Europe/Rome', 'GMT+02:00 Europe/Rome'), ('Europe/San_Marino', 'GMT+02:00 Europe/San Marino'), ('Europe/Sarajevo', 'GMT+02:00 Europe/Sarajevo'), ('Europe/Skopje', 'GMT+02:00 Europe/Skopje'), ('Europe/Stockholm', 'GMT+02:00 Europe/Stockholm'), ('Europe/Tirane', 'GMT+02:00 Europe/Tirane'), ('Europe/Vaduz', 'GMT+02:00 Europe/Vaduz'), ('Europe/Vatican', 'GMT+02:00 Europe/Vatican'), ('Europe/Vienna', 'GMT+02:00 Europe/Vienna'), ('Europe/Warsaw', 'GMT+02:00 Europe/Warsaw'), ('Europe/Zagreb', 'GMT+02:00 Europe/Zagreb'), ('Europe/Zurich', 'GMT+02:00 Europe/Zurich'), ('Africa/Addis_Ababa', 'GMT+03:00 Africa/Addis Ababa'), ('Africa/Asmara', 'GMT+03:00 Africa/Asmara'), ('Africa/Dar_es_Salaam', 'GMT+03:00 Africa/Dar es Salaam'), ('Africa/Djibouti', 'GMT+03:00 Africa/Djibouti'), ('Africa/Juba', 'GMT+03:00 Africa/Juba'), ('Africa/Kampala', 'GMT+03:00 Africa/Kampala'), ('Africa/Mogadishu', 'GMT+03:00 Africa/Mogadishu'), ('Africa/Nairobi', 'GMT+03:00 Africa/Nairobi'), ('Antarctica/Syowa', 'GMT+03:00 Antarctica/Syowa'), ('Asia/Aden', 'GMT+03:00 Asia/Aden'), ('Asia/Amman', 'GMT+03:00 Asia/Amman'), ('Asia/Baghdad', 'GMT+03:00 Asia/Baghdad'), ('Asia/Bahrain', 'GMT+03:00 Asia/Bahrain'), ('Asia/Beirut', 'GMT+03:00 Asia/Beirut'), ('Asia/Damascus', 'GMT+03:00 Asia/Damascus'), ('Asia/Famagusta', 'GMT+03:00 Asia/Famagusta'), ('Asia/Gaza', 'GMT+03:00 Asia/Gaza'), ('Asia/Hebron', 'GMT+03:00 Asia/Hebron'), ('Asia/Jerusalem', 'GMT+03:00 Asia/Jerusalem'), ('Asia/Kuwait', 'GMT+03:00 Asia/Kuwait'), ('Asia/Nicosia', 'GMT+03:00 Asia/Nicosia'), ('Asia/Qatar', 'GMT+03:00 Asia/Qatar'), ('Asia/Riyadh', 'GMT+03:00 Asia/Riyadh'), ('Europe/Athens', 'GMT+03:00 Europe/Athens'), ('Europe/Bucharest', 'GMT+03:00 Europe/Bucharest'), ('Europe/Chisinau', 'GMT+03:00 Europe/Chisinau'), ('Europe/Helsinki', 'GMT+03:00 Europe/Helsinki'), ('Europe/Istanbul', 'GMT+03:00 Europe/Istanbul'), ('Europe/Kiev', 'GMT+03:00 Europe/Kiev'), ('Europe/Kirov', 'GMT+03:00 Europe/Kirov'), ('Europe/Mariehamn', 'GMT+03:00 Europe/Mariehamn'), ('Europe/Minsk', 'GMT+03:00 Europe/Minsk'), ('Europe/Moscow', 'GMT+03:00 Europe/Moscow'), ('Europe/Riga', 'GMT+03:00 Europe/Riga'), ('Europe/Simferopol', 'GMT+03:00 Europe/Simferopol'), ('Europe/Sofia', 'GMT+03:00 Europe/Sofia'), ('Europe/Tallinn', 'GMT+03:00 Europe/Tallinn'), ('Europe/Uzhgorod', 'GMT+03:00 Europe/Uzhgorod'), ('Europe/Vilnius', 'GMT+03:00 Europe/Vilnius'), ('Europe/Volgograd', 'GMT+03:00 Europe/Volgograd'), ('Europe/Zaporozhye', 'GMT+03:00 Europe/Zaporozhye'), ('Indian/Antananarivo', 'GMT+03:00 Indian/Antananarivo'), ('Indian/Comoro', 'GMT+03:00 Indian/Comoro'), ('Indian/Mayotte', 'GMT+03:00 Indian/Mayotte'), ('Asia/Baku', 'GMT+04:00 Asia/Baku'), ('Asia/Dubai', 'GMT+04:00 Asia/Dubai'), ('Asia/Muscat', 'GMT+04:00 Asia/Muscat'), ('Asia/Tbilisi', 'GMT+04:00 Asia/Tbilisi'), ('Asia/Yerevan', 'GMT+04:00 Asia/Yerevan'), ('Europe/Astrakhan', 'GMT+04:00 Europe/Astrakhan'), ('Europe/Samara', 'GMT+04:00 Europe/Samara'), ('Europe/Saratov', 'GMT+04:00 Europe/Saratov'), ('Europe/Ulyanovsk', 'GMT+04:00 Europe/Ulyanovsk'), ('Indian/Mahe', 'GMT+04:00 Indian/Mahe'), ('Indian/Mauritius', 'GMT+04:00 Indian/Mauritius'), ('Indian/Reunion', 'GMT+04:00 Indian/Reunion'), ('Asia/Kabul', 'GMT+04:30 Asia/Kabul'), ('Asia/Tehran', 'GMT+04:30 Asia/Tehran'), ('Antarctica/Mawson', 'GMT+05:00 Antarctica/Mawson'), ('Asia/Aqtau', 'GMT+05:00 Asia/Aqtau'), ('Asia/Aqtobe', 'GMT+05:00 Asia/Aqtobe'), ('Asia/Ashgabat', 'GMT+05:00 Asia/Ashgabat'), ('Asia/Atyrau', 'GMT+05:00 Asia/Atyrau'), ('Asia/Dushanbe', 'GMT+05:00 Asia/Dushanbe'), ('Asia/Karachi', 'GMT+05:00 Asia/Karachi'), ('Asia/Oral', 'GMT+05:00 Asia/Oral'), ('Asia/Samarkand', 'GMT+05:00 Asia/Samarkand'), ('Asia/Tashkent', 'GMT+05:00 Asia/Tashkent'), ('Asia/Yekaterinburg', 'GMT+05:00 Asia/Yekaterinburg'), ('Indian/Kerguelen', 'GMT+05:00 Indian/Kerguelen'), ('Indian/Maldives', 'GMT+05:00 Indian/Maldives'), ('Asia/Colombo', 'GMT+05:30 Asia/Colombo'), ('Asia/Kolkata', 'GMT+05:30 Asia/Kolkata'), ('Asia/Kathmandu', 'GMT+05:45 Asia/Kathmandu'), ('Antarctica/Vostok', 'GMT+06:00 Antarctica/Vostok'), ('Asia/Almaty', 'GMT+06:00 Asia/Almaty'), ('Asia/Bishkek', 'GMT+06:00 Asia/Bishkek'), ('Asia/Dhaka', 'GMT+06:00 Asia/Dhaka'), ('Asia/Omsk', 'GMT+06:00 Asia/Omsk'), ('Asia/Qyzylorda', 'GMT+06:00 Asia/Qyzylorda'), ('Asia/Thimphu', 'GMT+06:00 Asia/Thimphu'), ('Asia/Urumqi', 'GMT+06:00 Asia/Urumqi'), ('Indian/Chagos', 'GMT+06:00 Indian/Chagos'), ('Asia/Yangon', 'GMT+06:30 Asia/Yangon'), ('Indian/Cocos', 'GMT+06:30 Indian/Cocos'), ('Antarctica/Davis', 'GMT+07:00 Antarctica/Davis'), ('Asia/Bangkok', 'GMT+07:00 Asia/Bangkok'), ('Asia/Barnaul', 'GMT+07:00 Asia/Barnaul'), ('Asia/Ho_Chi_Minh', 'GMT+07:00 Asia/Ho Chi Minh'), ('Asia/Hovd', 'GMT+07:00 Asia/Hovd'), ('Asia/Jakarta', 'GMT+07:00 Asia/Jakarta'), ('Asia/Krasnoyarsk', 'GMT+07:00 Asia/Krasnoyarsk'), ('Asia/Novokuznetsk', 'GMT+07:00 Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'GMT+07:00 Asia/Novosibirsk'), ('Asia/Phnom_Penh', 'GMT+07:00 Asia/Phnom Penh'), ('Asia/Pontianak', 'GMT+07:00 Asia/Pontianak'), ('Asia/Tomsk', 'GMT+07:00 Asia/Tomsk'), ('Asia/Vientiane', 'GMT+07:00 Asia/Vientiane'), ('Indian/Christmas', 'GMT+07:00 Indian/Christmas'), ('Antarctica/Casey', 'GMT+08:00 Antarctica/Casey'), ('Asia/Brunei', 'GMT+08:00 Asia/Brunei'), ('Asia/Choibalsan', 'GMT+08:00 Asia/Choibalsan'), ('Asia/Hong_Kong', 'GMT+08:00 Asia/Hong Kong'), ('Asia/Irkutsk', 'GMT+08:00 Asia/Irkutsk'), ('Asia/Kuala_Lumpur', 'GMT+08:00 Asia/Kuala Lumpur'), ('Asia/Kuching', 'GMT+08:00 Asia/Kuching'), ('Asia/Macau', 'GMT+08:00 Asia/Macau'), ('Asia/Makassar', 'GMT+08:00 Asia/Makassar'), ('Asia/Manila', 'GMT+08:00 Asia/Manila'), ('Asia/Shanghai', 'GMT+08:00 Asia/Shanghai'), ('Asia/Singapore', 'GMT+08:00 Asia/Singapore'), ('Asia/Taipei', 'GMT+08:00 Asia/Taipei'), ('Asia/Ulaanbaatar', 'GMT+08:00 Asia/Ulaanbaatar'), ('Australia/Perth', 'GMT+08:00 Australia/Perth'), ('Australia/Eucla', 'GMT+08:45 Australia/Eucla'), ('Asia/Chita', 'GMT+09:00 Asia/Chita'), ('Asia/Dili', 'GMT+09:00 Asia/Dili'), ('Asia/Jayapura', 'GMT+09:00 Asia/Jayapura'), ('Asia/Khandyga', 'GMT+09:00 Asia/Khandyga'), ('Asia/Pyongyang', 'GMT+09:00 Asia/Pyongyang'), ('Asia/Seoul', 'GMT+09:00 Asia/Seoul'), ('Asia/Tokyo', 'GMT+09:00 Asia/Tokyo'), ('Asia/Yakutsk', 'GMT+09:00 Asia/Yakutsk'), ('Pacific/Palau', 'GMT+09:00 Pacific/Palau'), ('Australia/Adelaide', 'GMT+09:30 Australia/Adelaide'), ('Australia/Broken_Hill', 'GMT+09:30 Australia/Broken Hill'), ('Australia/Darwin', 'GMT+09:30 Australia/Darwin'), ('Antarctica/DumontDUrville', 'GMT+10:00 Antarctica/DumontDUrville'), ('Asia/Ust-Nera', 'GMT+10:00 Asia/Ust-Nera'), ('Asia/Vladivostok', 'GMT+10:00 Asia/Vladivostok'), ('Australia/Brisbane', 'GMT+10:00 Australia/Brisbane'), ('Australia/Currie', 'GMT+10:00 Australia/Currie'), ('Australia/Hobart', 'GMT+10:00 Australia/Hobart'), ('Australia/Lindeman', 'GMT+10:00 Australia/Lindeman'), ('Australia/Melbourne', 'GMT+10:00 Australia/Melbourne'), ('Australia/Sydney', 'GMT+10:00 Australia/Sydney'), ('Pacific/Chuuk', 'GMT+10:00 Pacific/Chuuk'), ('Pacific/Guam', 'GMT+10:00 Pacific/Guam'), ('Pacific/Port_Moresby', 'GMT+10:00 Pacific/Port Moresby'), ('Pacific/Saipan', 'GMT+10:00 Pacific/Saipan'), ('Australia/Lord_Howe', 'GMT+10:30 Australia/Lord Howe'), ('Antarctica/Macquarie', 'GMT+11:00 Antarctica/Macquarie'), ('Asia/Magadan', 'GMT+11:00 Asia/Magadan'), ('Asia/Sakhalin', 'GMT+11:00 Asia/Sakhalin'), ('Asia/Srednekolymsk', 'GMT+11:00 Asia/Srednekolymsk'), ('Pacific/Bougainville', 'GMT+11:00 Pacific/Bougainville'), ('Pacific/Efate', 'GMT+11:00 Pacific/Efate'), ('Pacific/Guadalcanal', 'GMT+11:00 Pacific/Guadalcanal'), ('Pacific/Kosrae', 'GMT+11:00 Pacific/Kosrae'), ('Pacific/Norfolk', 'GMT+11:00 Pacific/Norfolk'), ('Pacific/Noumea', 'GMT+11:00 Pacific/Noumea'), ('Pacific/Pohnpei', 'GMT+11:00 Pacific/Pohnpei'), ('Antarctica/McMurdo', 'GMT+12:00 Antarctica/McMurdo'), ('Asia/Anadyr', 'GMT+12:00 Asia/Anadyr'), ('Asia/Kamchatka', 'GMT+12:00 Asia/Kamchatka'), ('Pacific/Auckland', 'GMT+12:00 Pacific/Auckland'), ('Pacific/Fiji', 'GMT+12:00 Pacific/Fiji'), ('Pacific/Funafuti', 'GMT+12:00 Pacific/Funafuti'), ('Pacific/Kwajalein', 'GMT+12:00 Pacific/Kwajalein'), ('Pacific/Majuro', 'GMT+12:00 Pacific/Majuro'), ('Pacific/Nauru', 'GMT+12:00 Pacific/Nauru'), ('Pacific/Tarawa', 'GMT+12:00 Pacific/Tarawa'), ('Pacific/Wake', 'GMT+12:00 Pacific/Wake'), ('Pacific/Wallis', 'GMT+12:00 Pacific/Wallis'), ('Pacific/Chatham', 'GMT+12:45 Pacific/Chatham'), ('Pacific/Apia', 'GMT+13:00 Pacific/Apia'), ('Pacific/Enderbury', 'GMT+13:00 Pacific/Enderbury'), ('Pacific/Fakaofo', 'GMT+13:00 Pacific/Fakaofo'), ('Pacific/Tongatapu', 'GMT+13:00 Pacific/Tongatapu'), ('Pacific/Kiritimati', 'GMT+14:00 Pacific/Kiritimati')], default='America/Chicago'),
        ),
    ]

Unable to set field label

TimeZoneField currently does not accept custom label, either via first positioning argument:

tz = TimeZoneField('Custom Time Zone', null=True, blank=True)

ValueError: need more than 1 value to unpack

Error when accessing changed_data in a ModelForm that uses TimeZoneFormField

I added TimeZoneField to my User Profile Model.
I added TimeZoneFormField to a simple Form.

I instantiated the form passing the user's timezone as part of the initial dictionary.

form = SettingsForm(initial={'language': user.language, 'email': user.email, 'timezone': user.timezone})

In one of the form's clean_field methods, I access self.changed_data and an exception is raised because it's assuming that 'timezone' is a string and it's trying to uppercase it.

'America/Mexico_City' object has no attribute 'upper'.

The exception is thrown at this line:
if zone.upper() == 'UTC':
python3.6/site-packages/pytz/__init__.py in timezone, line 162

Here is the form:

class SettingsForm(Form):
    language = forms.ChoiceField(choices=settings.LANGUAGES)
    email = forms.EmailField()
    timezone = timezone_field.TimeZoneFormField()

    def clean_email(self):
        email = self.cleaned_data.get('email')

        if 'email' not in self.changed_data: # The exception is thrown when accessing changed_data
            return email

        if AuthUser.objects.filter(email=email).exists():
            raise ValidationError(_('That email already exists.'), code='email_exists')

        return email

TypeError: is not JSON serializable with django rest framework

Hello,

I'm using the timezone field along with django rest framework. With the 1.2 version everything worked out of the box. But with the 1.3 version i got this error when my model is rendered:

TypeError: <DstTzInfo 'Europe/Zurich' BMT+0:30:00 STD> is not JSON serializable

I had to use a home made DRF Field to return the string value of the timezone field of my model.

class BBTZField(serializers.Field):
    def to_representation(self, obj):
        return six.text_type(obj.zone)

Is this change wanted or known ?

Here is my pip freeze:

djangorestframework==3.3.1
django-timezone-field==1.3
Django==1.8.6

Thanks for your help.

Deconstruct in makemigrations

I have my own addon on makemigrations, I think it is quite rediculous that django migrations react to language differences in field arguments like 'verbose_name', 'help_text', 'related_name or 'choices'

so i override the makemigations.py by:

IGNORED_ATTRS = ['verbose_name', 'help_text', 'related_name', 'choices']
original_deconstruct = models.Field.deconstruct

def new_deconstruct(self):
    name, path, args, kwargs = original_deconstruct(self)
    for attr in IGNORED_ATTRS:
        kwargs.pop(attr, None)
    return name, path, args, kwargs

models.Field.deconstruct = new_deconstruct

This works well for all packages, except for this one (django-timezone-field), there i got:

an error on the fields.py line 79 (version 3.0 for python 2.7)

def deconstruct(self):
    name, path, args, kwargs = super(TimeZoneField, self).deconstruct()
    if kwargs['choices'] == self.CHOICES:
        del kwargs['choices']

so is it possible for you to change the code, and first check if the key is in the kwargs?, like for example:

if 'choices'in kwargs and kwargs['choices'] == self.CHOICES:

the same for the line below (max_length), not needed for me, but just in case....

Breaking changes in 1.3

We just noticed a new failing build as of last night and tracked down the issue to a change in the default value for null in this field. It used to default to null=True, but now it is defaulting to null=False which is causing some of our validation to fail.

Running django-timezone-field @ 04566d1

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from timezone_field import fields
>>> fields.TimeZoneField()
<timezone_field.fields.TimeZoneField>
>>> fields.TimeZoneField().null
True
>>> exit()

Running django-timezone-field @ 80ab1ec

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from timezone_field import fields
>>> fields.TimeZoneField().null
False
>>> exit()

This appears to have been caused by 71f107e, which suggests that the previous default should have been null=True and this counts as a bugfix. If you check line 61 of that diff, you'll notice that the logic used to explicitly specify True as the default. This may also be related to #23, which inspired the commit before that one.

We've fixed this by explicitly specifying null=True (which we know isn't optimal for a CharField) for now.

CHOICES does not contain the actual values stored in the DB

Hi there,

The choices attribute of TimeZoneField contains pytz objects rather than database-ready values,

(https://github.com/mfogel/django-timezone-field/blob/develop/timezone_field/fields.py#L36)

    CHOICES = [(pytz.timezone(tz), tz) for tz in pytz.all_timezones]

This contradicts https://docs.djangoproject.com/en/dev/ref/models/fields/#choices.

The TimeZoneField compensates for this by doing the conversion in get_prep_value.

This makes sense, for the most part, but has caused burke-software/django-report-builder#93. In general, any third party tool matching the value pulled from the DB will not be able to match it effectively against the choices list.

Perhaps the choices list could contain the string representation of the time zone, and the conversion to a Python value could be performed elsewhere? I have made custom fields, but never one quite like this.

Kenn

TimeZoneFormField code does not install from PIP.

Just wanted to make you aware that the direct PIP install is broken. When installing directly from PIP (not via GIT), the form field code does not get installed. Reinstalling using the GIT install corrects the issue, i.e.:

This works:

pip install git+git://github.com/mfogel/django-timezone-field.git

This does NOT work, at least for the form fields:

pip install django-timezone-field

Great package, BTW! Thanks! I especially like that you included the South introspection rules. Bravo!

Bob S.

shouldn't TimeZoneFormField and TimeZoneFieldBase choices init be the same ?

TimeZoneFieldBase choices is based on pytz.common_timezones while TimeZoneFormField is based on pytz.all_timezones
Shouldn't they be based on the same initial list of choices ? In case you create a form with TimeZoneFormField, you offer choices to the user that are not, by default, compatible with TimeZoneFieldBase validator.

Django 1.9 Exception: no `_choices` attribute

I realize Django 1.9 isn't out yet, but I'm seeing this error/traceback:

Traceback (most recent call last):
  File "./manage.py", line 25, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/.virtualenvs/proj/src/django/django/core/management/__init__.py", line 331, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/.virtualenvs/proj/src/django/django/core/management/__init__.py", line 305, in execute
    django.setup()
  File "/home/vagrant/.virtualenvs/proj/src/django/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/vagrant/.virtualenvs/proj/src/django/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/vagrant/.virtualenvs/proj/src/django/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/home/vagrant/.virtualenvs/proj/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2231, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2214, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1448, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/vagrant/users/models/__init__.py", line 1, in <module>
    from .auth import *
  File "/vagrant/users/models/auth.py", line 27, in <module>
    class User(PermissionsMixin, TimeStampedModelMixin, DrupalNodeModelMixin, AbstractBaseUser):
  File "/vagrant/users/models/auth.py", line 71, in User
    timezone = TimeZoneField(default=pytz.UTC)
  File "/home/vagrant/.virtualenvs/proj/lib/python3.4/site-packages/timezone_field/fields.py", line 53, in __init__
    if self._choices:
AttributeError: 'TimeZoneField' object has no attribute '_choices'

This may be related to #24 perhaps, as I am seeing the same deprecation warning too.

Ability to have offsets in form field

Hi,
Besides just showing drop-down box with names of timezones, it would be nice to show them with offsets, in parenthesis maybe. It is usual practice on a lot of websites (example is from crowdin, but I think you are aware of what I am referring to)

slika

Maybe not as default behavior, but controllable over settings (not sure, just throwing ideas)

Cannot serialize model with TimeZone field using DjangoJSONEncoder

Hello,
I'm using Django 1.6.11 (I can't migrate to Django 1.7 yet, because our codebase is huge and switching to Django 1.7 causes immense breakage) and django-allauth 0.19.1.

Unfortunately for me, django-allauth attempts to serialize my custom User model to JSON, and there's no way to overcome this.

But DjangoJSONEncoder fails on the timezone field telling that:

Traceback:
File "/data/cache/buildout/eggs/Django-1.6.11-py2.7.egg/django/core/handlers/base.py" in get_response
112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/socialaccount/providers/facebook/views.py" in login_by_token
77.                     ret = complete_social_login(request, login)
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/socialaccount/helpers.py" in complete_social_login
145.         return _complete_social_login(request, sociallogin)
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/socialaccount/helpers.py" in _complete_social_login
161.         ret = _process_signup(request, sociallogin)
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/socialaccount/helpers.py" in _process_signup
27.         request.session['socialaccount_sociallogin'] = sociallogin.serialize()
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/socialaccount/models.py" in serialize
186.                    user=serialize_instance(self.user),
File "/data/cache/buildout/eggs/django_allauth-0.19.1-py2.7.egg/allauth/utils.py" in serialize_instance
161.     return json.loads(json.dumps(ret, cls=DjangoJSONEncoder))
File "/usr/lib/python2.7/json/__init__.py" in dumps
250.         sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
207.         chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
270.         return _iterencode(o, 0)
File "/data/cache/buildout/eggs/Django-1.6.11-py2.7.egg/django/core/serializers/json.py" in default
104.             return super(DjangoJSONEncoder, self).default(o)
File "/usr/lib/python2.7/json/encoder.py" in default
184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /auth/facebook/login/token/
Exception Value: <UTC> is not JSON serializable

I've browsed closed issues and I guess this problem was solved if you use Django 1.7. But I have a deadline and migrating the whole project to Django 1.7 is not a viable workaround. Django 1.6 is still supported, so maybe you can fix the code to support 1.6? Or offer some workaround? I see some workarounds in closed tickets, but they're pretty ugly.

I'm using the latest timezone field from PyPI (1.2).

'TimeZoneField' has no attribute 'default_choices'

After upgrading django-timezone-field to v4.2, Django (v2.2.24) application is not able to initialize:

    def crontab_schedule_celery_timezone():
        """Return timezone string from Django settings `CELERY_TIMEZONE` variable.

        If is not defined or is not a valid timezone, return `"UTC"` instead.
        """
        try:
            CELERY_TIMEZONE = getattr(
                settings, '%s_TIMEZONE' % current_app.namespace)
        except AttributeError:
            return 'UTC'
        return CELERY_TIMEZONE if CELERY_TIMEZONE in [
>           choice[0].zone for choice in timezone_field.
            TimeZoneField.default_choices
        ] else 'UTC'
E       AttributeError: type object 'TimeZoneField' has no attribute 'default_choices'

../.local/lib/python3.8/site-packages/django_celery_beat/models.py:70: AttributeError

pytz.exceptions.AmbiguousTimeError during DST changes if created with choices_display='WITH_GMT_OFFSET'

Whenever you try to initialize a model with a TimeZone field during an a DST change in any of the timezones supported by pytz you'll get the following exception:


 File ".../devel/backend/env/lib/python3.7/site-packages/timezone_field/fields.py", line 72, in __init__                                                          
    choices = with_gmt_offset(values)                                                                                                                                                                      
  File ".../devel/backend/env/lib/python3.7/site-packages/timezone_field/choices.py", line 34, in with_gmt_offset                                                  
    delta = pytz.timezone(tz_str).utcoffset(now)                                                                                                                                                           
  File ".../devel/backend/env/lib/python3.7/site-packages/pytz/tzinfo.py", line 422, in utcoffset                                                                  
    dt = self.localize(dt, is_dst)                                                                                                                                                                         
  File ".../devel/backend/env/lib/python3.7/site-packages/pytz/tzinfo.py", line 363, in localize                                                                   
    raise AmbiguousTimeError(dt)                                                                                                                                                                           
pytz.exceptions.AmbiguousTimeError: 2021-04-03 23:44:14.162132

To test this you'd probably want to use freezegun (or something similar) with a unit test. You can use the above timestamp as an example. (It should produce an error when evaluating the America/Santiago timezone.)

Now looking into your code (with_gmt_offset in choices.py) the logic doesn't even seem valid. pytz.timezone(...).utcoffset will tell you the UTC offset of the provided timestamp. I.e. the utc offset of the specified timezone at provided timestamp. But you are passing in the utctimestamp and this will provide a bogus result around the DST (even if you do fix the above error). Because it will tell you the utc offset not for the current time but for the time returned by utcnow. Which will be offset by the utc offset itself... So e.g. I'm in Europe, which means I'm UTC+1 (without DST), so when I get to the DST change (transitioning to UTC+2) your algorithm will show me I'm in UTC+1 for until an hour after the actual DST change.

Now I think the whole algoritm could be a lot simpler. You just create the timezone instances, then you create localized datetimes and get the utcoffset for those. This removes the whole issue (the guesswork that pytz has to do).

Because then you go UTC -> localized timestamp, which is unambiguous. The localized timestamp (based on the UTC) will contain the correct timezone (either DST or non-DST) and you can get the offset from that without any guesswork. (Again, the guesswork is hidden in pytz.)

Show TimeZoneField example with a default

Since I was adding a field using South it wanted a default

Might be worth showing an example with one... mine currently looks like:

class Location(models.Model):
    timezone = TimeZoneField(default='Europe/London')

Object of type 'Europe/Amsterdam' is not JSON serializable

Using:

Django==2.2.6
djangorestframework==3.10.3
django-timezone-field==3.1

Having a simple Django model with a TimeZonefield:

from timezone_field import TimeZoneField

class Event(models.Model):
    event_tz = TimeZoneField(default=settings.TIME_ZONE)

and a simple DRF modelserializer:

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = Event
        fields = (
            'id',
        )

Note that I don't event display the event_tz field.
I get the error: Object of type 'Europe/Amsterdam' is not JSON serializable when I display a detail page with this serializer.

Any idea what could have caused this?

is INSTALLED_APPS needed?

I was wondering why is it important or necessary to add timezone_field to INSTALLED_APPS?

I cannot see timezone_field hooking indo Django in anyway, except by providing tools (fields) that do not really need to exist in an installed app.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.