Django 1.9.2 AssertionError: database connection isn't set to UTC

17,062

Solution 1

I encountered this same problem, also with a server that is normally running with the UTC+2 (in my case, Europe/Oslo).

It turned out that the system zoneinfo files on my server (Centos 7) were corrupted, which became evident in pg_timezone_names.

postgres=# select * from pg_timezone_names where name like 'UTC';
 name | abbrev | utc_offset | is_dst
------+--------+------------+--------
 UTC  | CEST   | 02:00:00   | t
(1 row)

After running yum update tzdata to update my server's timezone files, and restarting the PostgreSQL server, the issue appears to be resolved.

postgres=# select * from pg_timezone_names where name like 'UTC';
 name | abbrev | utc_offset | is_dst
------+--------+------------+--------
 UTC  | UTC    | 00:00:00   | f
(1 row)

My guess it that I might previously have run cat /usr/share/zoneinfo/Europe/Oslo > /etc/localtime without first removing /etc/localtime to change the timezone on the system, effectively overwriting the zoneinfo for UTC with the zoneinfo for Europe/Oslo.

Solution 2

For 18/06/2021 this is a known issue, which comes from the psycopg-2/psycopg2-binary packages. Fortunately, they already have an open issue on their GitHub page, so hopefully it gets fixed soon.

As a temporary fix, you can pin the version in your requirements.txt to psycopg2-binary>=2.8,<2.9 or psycopg2>=2.8,<2.9, depending on what package you are using.

Thanks to @vinkomlacic for mentioning this in comments.

Solution 3

Here's a simple workaround that I found to fix the issue for me. That is to set:

USE_TZ = False

This helps to solve the issue. By default it is set to True, so that gives the error for me when I use PostgreSql on Heroku. Maybe some synchronization happens between Django engine and the database.

Solution 4

If you are using psycopg2 2.9, downgrade to psycopg2==2.8.6 or pip3 install psycopg2-binary==2.8.6. This issue is caused by a recent update to psycopg2, version 2.9.

Solution 5

Thanks very much for the answer KFH, it helped me a lot. In case you are using Ubuntu, the following should fix it:

sudo apt install tzdata --reinstall

The problem was the same for me, as I had previously run sudo cp /usr/share/zoneinfo/America/Montreal /etc/localtime which messed with my postgres db. Re-installing tzdata and restarting postgres fixed the problem for me.

Share:
17,062

Related videos on Youtube

Lars Olafsson
Author by

Lars Olafsson

BY DAY: Solution Architect at Olafsson Consulting BY NIGHT: Working on non-profit and spending time with friends and family FOR FUN: Badminton, diving, helping where i can "If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers

Updated on September 15, 2022

Comments

  • Lars Olafsson
    Lars Olafsson over 1 year

    I have setup 3 servers now with PostgreSQL and have so far not seen this issue. I am now setting up the first server which is not running on a danish server, and i start getting errors when accessing the database from the web.

    I could use createsuperuser without issues and it created my super user. But when i try to use it to login to my site i get the error.

    File "/usr/lib64/python3.4/site-packages/django/db/models/sql/compiler.py",    line 1239, in cursor_iter
    sentinel):
    File "/usr/lib64/python3.4/site-packages/django/db/models/sql/compiler.py", line 1238, in <lambda>
    for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
    File "/usr/lib64/python3.4/site-packages/django/db/utils.py", line 102, in  inner
    return func(*args, **kwargs)
    File "/usr/lib64/python3.4/site-packages/django/db/backends/postgresql/utils.py", line 6, in utc_tzinfo_factory
    raise AssertionError("database connection isn't set to UTC")
    AssertionError: database connection isn't set to UTC
    

    I have been looking at the code and the error comes from this code.

    from django.utils.timezone import utc
    def utc_tzinfo_factory(offset):
        if offset != 0:
        raise AssertionError("database connection isn't set to UTC")
    return utc
    

    Though i cannot find where offset is initiated, so i cannot figure out how Django decides that my offset is off.

    My postgresql database have timezone set to UTC and have verified all postgresql parameters written in the django documentation and i am now running out of ideas of why this happens.

    I hope someone here can help?

    python3.4 -V: Python 3.4.3

    psql -V: psql (PostgreSQL) 9.2.15

    django-admin --version: 1.9.2

    UPDATED 11/8-2016 - Full Stack from DEBUG view

    I found the value for the offset in the utc_tzinfo_factory, it has the value of 120. Though i cannot explain how or why it gets this value.

    Below is a copy from the debug page of Django for the error with full stack and variables.

    Environment:
    
    
    Request Method: POST
    Request URL: http://myweb.dk/accounts/login/
    
    Django Version: 1.9.2
    Python Version: 3.4.3
    Installed Applications:
    ['polls.apps.PollsConfig',
     'teamTournamentApp.apps.TeamtournamentappConfig',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles']
    Installed Middleware:
    ['django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']
    
    
    
    Traceback:
    
    File "/usr/lib64/python3.4/site-packages/django/core/handlers/base.py" in get_response
      149.                     response = self.process_exception_by_middleware(e, request)
    
    File "/usr/lib64/python3.4/site-packages/django/core/handlers/base.py" in get_response
      147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/views.py" in inner
      49.         return func(*args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
      76.             return view(request, *args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
      149.                     response = view_func(request, *args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
      57.         response = view_func(request, *args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/views.py" in login
      69.         if form.is_valid():
    
    File "/usr/lib64/python3.4/site-packages/django/forms/forms.py" in is_valid
      161.         return self.is_bound and not self.errors
    
    File "/usr/lib64/python3.4/site-packages/django/forms/forms.py" in errors
      153.             self.full_clean()
    
    File "/usr/lib64/python3.4/site-packages/django/forms/forms.py" in full_clean
      363.         self._clean_form()
    
    File "/usr/lib64/python3.4/site-packages/django/forms/forms.py" in _clean_form
      390.             cleaned_data = self.clean()
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/forms.py" in clean
      159.                                            password=password)
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/__init__.py" in authenticate
      74.             user = backend.authenticate(**credentials)
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/backends.py" in authenticate
      17.             user = UserModel._default_manager.get_by_natural_key(username)
    
    File "/usr/lib64/python3.4/site-packages/django/contrib/auth/base_user.py" in get_by_natural_key
      45.         return self.get(**{self.model.USERNAME_FIELD: username})
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/manager.py" in manager_method
      122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/query.py" in get
      381.         num = len(clone)
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/query.py" in __len__
      240.         self._fetch_all()
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/query.py" in _fetch_all
      1074.             self._result_cache = list(self.iterator())
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/query.py" in __iter__
      68.         for row in compiler.results_iter(results):
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/sql/compiler.py" in results_iter
      805.         for rows in results:
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/sql/compiler.py" in cursor_iter
      1239.                          sentinel):
    
    File "/usr/lib64/python3.4/site-packages/django/db/models/sql/compiler.py" in <lambda>
      1238.         for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
    
    File "/usr/lib64/python3.4/site-packages/django/db/utils.py" in inner
      102.                 return func(*args, **kwargs)
    
    File "/usr/lib64/python3.4/site-packages/django/db/backends/postgresql/utils.py" in utc_tzinfo_factory
      6.         raise AssertionError("database connection isn't set to UTC")
    
    Exception Type: AssertionError at /accounts/login/
    Exception Value: database connection isn't set to UTC
    
    Request information
    
    GET
    No GET data
    POST
    Variable    Value
    next    
    ''
    password    
    'xxxxxxx'
    username    
    'admin'
    csrfmiddlewaretoken 
    'f8E50d9kpS2j4Wlc7O9KsKtUXHxbuX58'
    FILES
    No FILES data
    COOKIES
    Variable    Value
    _ga 
    'GA1.2.1308578855.1465289038'
    csrftoken   
    'f8E50d9kpS2j4Wlc7O9KsKtUXHxbuX58'
    META
    Variable    Value
    UNIQUE_ID   
    'xxxxx'
    HTTP_USER_AGENT 
    ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like '
     'Gecko) Chrome/51.0.2704.103 Safari/537.36')
    mod_wsgi.total_requests 
    1
    REMOTE_ADDR 
    'xx.yy.zz.tt'
    mod_wsgi.handler_script 
    ''
    mod_wsgi.script_name    
    ''
    HTTP_ACCEPT 
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
    REQUEST_SCHEME  
    'http'
    mod_wsgi.script_start   
    '1470934394985429'
    HTTP_REFERER    
    'http://myweb.dk/accounts/login/'
    mod_wsgi.version    
    (4, 5, 3)
    SERVER_PROTOCOL 
    'HTTP/1.1'
    HTTP_HOST   
    'myweb.dk'
    wsgi.url_scheme 
    'http'
    HTTP_ACCEPT_ENCODING    
    'gzip, deflate'
    PATH_INFO   
    '/accounts/login/'
    wsgi.multiprocess   
    True
    HTTP_CONNECTION 
    'keep-alive'
    mod_wsgi.listener_port  
    '80'
    mod_wsgi.path_info  
    '/accounts/login/'
    CONTEXT_DOCUMENT_ROOT   
    '/var/www/vhosts/default/htdocs'
    REMOTE_PORT 
    '59723'
    wsgi.errors 
    <_io.TextIOWrapper encoding='utf-8'>
    mod_wsgi.callable_object    
    'application'
    SCRIPT_NAME 
    ''
    REQUEST_URI 
    '/accounts/login/'
    SCRIPT_FILENAME 
    '/var/www/vhosts/myweb.dk/httpdocs/TeamTournament/TeamTournament/wsgi.py'
    SERVER_ADMIN    
    '.....'
    mod_wsgi.request_start  
    '1470934394985053'
    mod_wsgi.listener_host  
    ''
    mod_wsgi.enable_sendfile    
    '0'
    HTTP_UPGRADE_INSECURE_REQUESTS  
    '1'
    mod_wsgi.script_reloading   
    '1'
    SERVER_SIGNATURE    
    ''
    mod_wsgi.application_group  
    'myweb.dk|'
    mod_wsgi.thread_requests    
    0
    wsgi.input  
    <mod_wsgi.Input object at 0x7f6266286920>
    QUERY_STRING    
    ''
    SERVER_ADDR 
    'xx.yy.zz.tt'
    wsgi.multithread    
    True
    wsgi.version    
    (1, 0)
    CONTEXT_PREFIX  
    ''
    wsgi.run_once   
    False
    REQUEST_METHOD  
    'POST'
    HTTP_ORIGIN 
    'http://myweb.dk'
    SERVER_NAME 
    'myweb.dk'
    mod_wsgi.request_handler    
    'wsgi-script'
    mod_wsgi.process_group  
    ''
    CONTENT_TYPE    
    'application/x-www-form-urlencoded'
    HTTP_CACHE_CONTROL  
    'max-age=0'
    SERVER_SOFTWARE 
    'Apache'
    HTTP_COOKIE 
    '_ga=GA1.2.1308578855.1465289038; csrftoken=f8E50d9kpS2j4Wlc7O9KsKtUXHxbuX58'
    HTTP_ACCEPT_LANGUAGE    
    'da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4,sv;q=0.2'
    SERVER_PORT 
    '80'
    wsgi.file_wrapper   
    ''
    apache.version  
    (2, 4, 6)
    PATH_TRANSLATED 
    '/var/www/vhosts/myweb.dk/httpdocs/TeamTournament/TeamTournament/wsgi.py/accounts/login/'
    CONTENT_LENGTH  
    '91'
    mod_wsgi.thread_id  
    2
    CSRF_COOKIE 
    'f8E50d9kpS2j4Wlc7O9KsKtUXHxbuX58'
    GATEWAY_INTERFACE   
    'CGI/1.1'
    DOCUMENT_ROOT   
    '/var/www/vhosts/default/htdocs'
    Settings
    Using settings module TeamTournament.settings
    Setting Value
    LOGIN_REDIRECT_URL  
    '/accounts/profile/'
    FILE_UPLOAD_HANDLERS    
    ['django.core.files.uploadhandler.MemoryFileUploadHandler',
     'django.core.files.uploadhandler.TemporaryFileUploadHandler']
    SECURE_SSL_HOST 
    None
    DATETIME_FORMAT 
    'N j, Y, P'
    EMAIL_HOST  
    'localhost'
    SESSION_COOKIE_PATH 
    '/'
    FORMAT_MODULE_PATH  
    None
    DEFAULT_TABLESPACE  
    ''
    DATE_INPUT_FORMATS  
    ['%Y-%m-%d',
     '%m/%d/%Y',
     '%m/%d/%y',
     '%b %d %Y',
     '%b %d, %Y',
     '%d %b %Y',
     '%d %b, %Y',
     '%B %d %Y',
     '%B %d, %Y',
     '%d %B %Y',
     '%d %B, %Y']
    TEMPLATE_DIRS   
    []
    DATETIME_INPUT_FORMATS  
    ['%Y-%m-%d %H:%M:%S',
     '%Y-%m-%d %H:%M:%S.%f',
     '%Y-%m-%d %H:%M',
     '%Y-%m-%d',
     '%m/%d/%Y %H:%M:%S',
     '%m/%d/%Y %H:%M:%S.%f',
     '%m/%d/%Y %H:%M',
     '%m/%d/%Y',
     '%m/%d/%y %H:%M:%S',
     '%m/%d/%y %H:%M:%S.%f',
     '%m/%d/%y %H:%M',
     '%m/%d/%y']
    FILE_UPLOAD_DIRECTORY_PERMISSIONS   
    None
    FILE_UPLOAD_MAX_MEMORY_SIZE 
    2621440
    FIRST_DAY_OF_WEEK   
    0
    STATICFILES_STORAGE 
    'django.contrib.staticfiles.storage.StaticFilesStorage'
    SESSION_ENGINE  
    'django.contrib.sessions.backends.db'
    TIME_FORMAT 
    'P'
    FORCE_SCRIPT_NAME   
    None
    SECURE_SSL_REDIRECT 
    False
    ALLOWED_INCLUDE_ROOTS   
    []
    SHORT_DATETIME_FORMAT   
    'm/d/Y P'
    DEFAULT_CONTENT_TYPE    
    'text/html'
    NUMBER_GROUPING 
    0
    DEFAULT_EXCEPTION_REPORTER_FILTER   
    'django.views.debug.SafeExceptionReporterFilter'
    SESSION_EXPIRE_AT_BROWSER_CLOSE 
    False
    LANGUAGE_CODE   
    'en-us'
    TIME_INPUT_FORMATS  
    ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
    SESSION_COOKIE_NAME 
    'sessionid'
    ALLOWED_HOSTS   
    ['xx.yy.zz.tt', 'myweb.net', 'myweb.dk']
    SESSION_COOKIE_DOMAIN   
    None
    EMAIL_SSL_CERTFILE  
    None
    DEFAULT_FROM_EMAIL  
    'webmaster@localhost'
    EMAIL_PORT  
    25
    DATE_FORMAT 
    'N j, Y'
    ABSOLUTE_URL_OVERRIDES  
    {}
    USE_ETAGS   
    False
    CSRF_FAILURE_VIEW   
    'django.views.csrf.csrf_failure'
    EMAIL_SSL_KEYFILE   
    '********************'
    CSRF_COOKIE_HTTPONLY    
    False
    SESSION_CACHE_ALIAS 
    'default'
    LANGUAGES   
    [('af', 'Afrikaans'),
     ('ar', 'Arabic'),
     ('ast', 'Asturian'),
     ('az', 'Azerbaijani'),
     ('bg', 'Bulgarian'),
     ('be', 'Belarusian'),
     ('bn', 'Bengali'),
     ('br', 'Breton'),
     ('bs', 'Bosnian'),
     ('ca', 'Catalan'),
     ('cs', 'Czech'),
     ('cy', 'Welsh'),
     ('da', 'Danish'),
     ('de', 'German'),
     ('el', 'Greek'),
     ('en', 'English'),
     ('en-au', 'Australian English'),
     ('en-gb', 'British English'),
     ('eo', 'Esperanto'),
     ('es', 'Spanish'),
     ('es-ar', 'Argentinian Spanish'),
     ('es-co', 'Colombian Spanish'),
     ('es-mx', 'Mexican Spanish'),
     ('es-ni', 'Nicaraguan Spanish'),
     ('es-ve', 'Venezuelan Spanish'),
     ('et', 'Estonian'),
     ('eu', 'Basque'),
     ('fa', 'Persian'),
     ('fi', 'Finnish'),
     ('fr', 'French'),
     ('fy', 'Frisian'),
     ('ga', 'Irish'),
     ('gd', 'Scottish Gaelic'),
     ('gl', 'Galician'),
     ('he', 'Hebrew'),
     ('hi', 'Hindi'),
     ('hr', 'Croatian'),
     ('hu', 'Hungarian'),
     ('ia', 'Interlingua'),
     ('id', 'Indonesian'),
     ('io', 'Ido'),
     ('is', 'Icelandic'),
     ('it', 'Italian'),
     ('ja', 'Japanese'),
     ('ka', 'Georgian'),
     ('kk', 'Kazakh'),
     ('km', 'Khmer'),
     ('kn', 'Kannada'),
     ('ko', 'Korean'),
     ('lb', 'Luxembourgish'),
     ('lt', 'Lithuanian'),
     ('lv', 'Latvian'),
     ('mk', 'Macedonian'),
     ('ml', 'Malayalam'),
     ('mn', 'Mongolian'),
     ('mr', 'Marathi'),
     ('my', 'Burmese'),
     ('nb', 'Norwegian Bokmal'),
     ('ne', 'Nepali'),
     ('nl', 'Dutch'),
     ('nn', 'Norwegian Nynorsk'),
     ('os', 'Ossetic'),
     ('pa', 'Punjabi'),
     ('pl', 'Polish'),
     ('pt', 'Portuguese'),
     ('pt-br', 'Brazilian Portuguese'),
     ('ro', 'Romanian'),
     ('ru', 'Russian'),
     ('sk', 'Slovak'),
     ('sl', 'Slovenian'),
     ('sq', 'Albanian'),
     ('sr', 'Serbian'),
     ('sr-latn', 'Serbian Latin'),
     ('sv', 'Swedish'),
     ('sw', 'Swahili'),
     ('ta', 'Tamil'),
     ('te', 'Telugu'),
     ('th', 'Thai'),
     ('tr', 'Turkish'),
     ('tt', 'Tatar'),
     ('udm', 'Udmurt'),
     ('uk', 'Ukrainian'),
     ('ur', 'Urdu'),
     ('vi', 'Vietnamese'),
     ('zh-hans', 'Simplified Chinese'),
     ('zh-hant', 'Traditional Chinese')]
    X_FRAME_OPTIONS 
    'SAMEORIGIN'
    AUTH_USER_MODEL 
    'auth.User'
    SILENCED_SYSTEM_CHECKS  
    []
    LOGOUT_URL  
    '/accounts/logout/'
    STATICFILES_FINDERS 
    ['django.contrib.staticfiles.finders.FileSystemFinder',
     'django.contrib.staticfiles.finders.AppDirectoriesFinder']
    TEMPLATES   
    [{'APP_DIRS': True,
      'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': ['/var/www/vhosts/myweb.dk/httpdocs/TeamTournament/templates'],
      'OPTIONS': {'context_processors': ['django.template.context_processors.debug',
                                         'django.template.context_processors.request',
                                         'django.contrib.auth.context_processors.auth',
                                         'django.contrib.messages.context_processors.messages',
                                         'django.template.context_processors.request']}}]
    SERVER_EMAIL    
    'root@localhost'
    SECURE_BROWSER_XSS_FILTER   
    False
    TEMPLATE_CONTEXT_PROCESSORS 
    ['django.contrib.auth.context_processors.auth',
     'django.template.context_processors.debug',
     'django.template.context_processors.i18n',
     'django.template.context_processors.media',
     'django.template.context_processors.static',
     'django.template.context_processors.tz',
     'django.contrib.messages.context_processors.messages']
    DEBUG_APPS  
    False
    USE_X_FORWARDED_PORT    
    False
    ADMINS  
    []
    SIGNING_BACKEND 
    'django.core.signing.TimestampSigner'
    CSRF_COOKIE_SECURE  
    False
    EMAIL_USE_SSL   
    False
    CACHES  
    {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
    LOCALE_PATHS    
    []
    TEMPLATE_STRING_IF_INVALID  
    ''
    MESSAGE_STORAGE 
    'django.contrib.messages.storage.fallback.FallbackStorage'
    PRODUCTION  
    False
    FIXTURE_DIRS    
    []
    CSRF_COOKIE_PATH    
    '/'
    MIDDLEWARE_CLASSES  
    ['django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']
    MANAGERS    
    []
    CSRF_TRUSTED_ORIGINS    
    []
    CACHE_MIDDLEWARE_SECONDS    
    600
    APPEND_SLASH    
    True
    TEST_NON_SERIALIZED_APPS    
    []
    SECURE_HSTS_INCLUDE_SUBDOMAINS  
    False
    MIGRATION_MODULES   
    {}
    LANGUAGE_COOKIE_AGE 
    None
    TEMPLATE_LOADERS    
    ['django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader']
    STATIC_URL  
    '/static/'
    SESSION_COOKIE_AGE  
    1209600
    SETTINGS_MODULE 
    'TeamTournament.settings'
    DECIMAL_SEPARATOR   
    '.'
    YEAR_MONTH_FORMAT   
    'F Y'
    EMAIL_TIMEOUT   
    None
    SESSION_SAVE_EVERY_REQUEST  
    False
    BASE_DIR    
    '/var/www/vhosts/myweb.dk/httpdocs/TeamTournament'
    SECURE_CONTENT_TYPE_NOSNIFF 
    False
    FILE_UPLOAD_TEMP_DIR    
    None
    CACHE_MIDDLEWARE_KEY_PREFIX 
    '********************'
    DEBUG   
    True
    SESSION_COOKIE_HTTPONLY 
    True
    CSRF_HEADER_NAME    
    'HTTP_X_CSRFTOKEN'
    USE_L10N    
    True
    STATICFILES_DIRS    
    []
    SESSION_SERIALIZER  
    'django.contrib.sessions.serializers.JSONSerializer'
    USE_THOUSAND_SEPARATOR  
    False
    EMAIL_BACKEND   
    'django.core.mail.backends.smtp.EmailBackend'
    USE_X_FORWARDED_HOST    
    False
    STATIC_ROOT 
    '/var/www/vhosts/myweb.dk/httpdocs/static/'
    SECRET_KEY  
    '********************'
    PASSWORD_RESET_TIMEOUT_DAYS 
    '********************'
    MEDIA_ROOT  
    ''
    TIME_ZONE   
    'CET'
    DATABASES   
    {'default': {'ATOMIC_REQUESTS': False,
                 'AUTOCOMMIT': True,
                 'CONN_MAX_AGE': 0,
                 'ENGINE': 'django.db.backends.postgresql',
                 'HOST': '127.0.0.1',
                 'NAME': 'user',
                 'OPTIONS': {},
                 'PASSWORD': '********************',
                 'PORT': '5432',
                 'TEST': {'CHARSET': None,
                          'COLLATION': None,
                          'MIRROR': None,
                          'NAME': None},
                 'TIME_ZONE': None,
                 'USER': 'user'}}
    DEFAULT_INDEX_TABLESPACE    
    ''
    EMAIL_USE_TLS   
    False
    LOGIN_URL   
    '/accounts/login/'
    SHORT_DATE_FORMAT   
    'm/d/Y'
    CSRF_COOKIE_NAME    
    'csrftoken'
    LANGUAGE_COOKIE_DOMAIN  
    None
    USE_I18N    
    True
    SESSION_COOKIE_SECURE   
    False
    CACHE_MIDDLEWARE_ALIAS  
    'default'
    DEFAULT_CHARSET 
    'utf-8'
    TEMPLATE_DEBUG  
    False
    ROOT_URLCONF    
    'TeamTournament.urls'
    SECURE_PROXY_SSL_HEADER 
    None
    EMAIL_HOST_PASSWORD 
    '********************'
    FILE_UPLOAD_PERMISSIONS 
    None
    CSRF_COOKIE_AGE 
    31449600
    DEBUG_PROPAGATE_EXCEPTIONS  
    False
    WSGI_APPLICATION    
    'TeamTournament.wsgi.application'
    PASSWORD_HASHERS    
    '********************'
    SECURE_REDIRECT_EXEMPT  
    []
    LANGUAGES_BIDI  
    ['he', 'ar', 'fa', 'ur']
    CSRF_COOKIE_DOMAIN  
    None
    DEFAULT_FILE_STORAGE    
    'django.core.files.storage.FileSystemStorage'
    POSTGRES    
    True
    PREPEND_WWW 
    False
    EMAIL_SUBJECT_PREFIX    
    '[Django] '
    LOGGING 
    {'disable_existing_loggers': False,
     'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}},
     'handlers': {'logfile': {'class': 'logging.handlers.WatchedFileHandler',
                              'filename': '/var/log/django/error.log'},
                  'mail_admins': {'class': 'django.utils.log.AdminEmailHandler',
                                  'filters': ['require_debug_false'],
                                  'level': 'ERROR'}},
     'loggers': {'django': {'handlers': ['logfile'],
                            'level': 'ERROR',
                            'propagate': False},
                 'django.request': {'handlers': ['mail_admins'],
                                    'level': 'ERROR',
                                    'propagate': True}},
     'version': 1}
    SESSION_FILE_PATH   
    None
    TEST_RUNNER 
    'django.test.runner.DiscoverRunner'
    INTERNAL_IPS    
    []
    DATABASE_ROUTERS    
    []
    FILE_CHARSET    
    'utf-8'
    LANGUAGE_COOKIE_NAME    
    'django_language'
    INSTALLED_APPS  
    ['polls.apps.PollsConfig',
     'teamTournamentApp.apps.TeamtournamentappConfig',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles']
    LANGUAGE_COOKIE_PATH    
    '/'
    IGNORABLE_404_URLS  
    []
    MEDIA_URL   
    ''
    DISALLOWED_USER_AGENTS  
    []
    LOG_PATH    
    '/var/log/django/error.log'
    LOGGING_CONFIG  
    'logging.config.dictConfig'
    THOUSAND_SEPARATOR  
    ','
    MONTH_DAY_FORMAT    
    'F j'
    USE_TZ  
    True
    EMAIL_HOST_USER 
    ''
    AUTH_PASSWORD_VALIDATORS    
    '********************'
    SECURE_HSTS_SECONDS 
    0
    AUTHENTICATION_BACKENDS 
    ['django.contrib.auth.backends.ModelBackend']
    
    • be_good_do_good
      be_good_do_good over 7 years
      What is the value of TIME_ZONE and USE_TZ in your settings.py?
    • Lars Olafsson
      Lars Olafsson over 7 years
      TIME_ZONE is CET and USE_TZ is True. I noticed my other servers have Europe/Copenhagen timezone in postgresql. And tried to change postgresql to this timezone. Same error. Also tried to change the TIME_ZONE to be UTC in settings and postgresql timezone is UTC. Still the same error.
    • MIkee
      MIkee over 5 years
      I have same issue. The pg_timezone_names shows correct info (UTC in both name and abbrev). If anyone else has solved this, help!
    • Lars Olafsson
      Lars Olafsson over 5 years
      Did you check the solution below? It solved it for me.
    • MIkee
      MIkee over 5 years
      Thanks for responding Lars. Yes, I checked pg_timezone_names both from psql and from with django shell. I only have this issue running django tests, not in the django dev or prod systems I am running, so I am looking further into why this only happens when running django tests
    • Lars Olafsson
      Lars Olafsson over 5 years
      If you create the dates in your test code. Then check what timezone you are using. It could be where the problem comes, because you have not activated the expected timezone in your test data, because it uses the local machine timezone, where when you use your browser it is using your computers timezone.
    • MIkee
      MIkee over 5 years
      @LarsOlafsson, exactly right. thank you sir. I added conn.execute("SET TIME ZONE 'UTC'") before my tests and it worked
    • vinkomlacic
      vinkomlacic almost 3 years
      @MIkee, had the same issue when I transferred the server on a Windows machine. The problem was the psycopg2 package. After setting psycopg2>=2.8,<2.9 in the requirements.txt, it worked fine.
    • MIkee
      MIkee almost 3 years
      Thanks vinkomlacic. I wound up re writing the code to use native Django ORM and ditched the raw sql in psycopg2. Strange because I use raw sql in many other places with no problem...
    • rahul rachh
      rahul rachh almost 3 years
      The error went away for me on windows by installing both: psycopg2==2.8.6 and psycopg2-binary==2.8.6 and uninstalling the latest version of any of both that were installed.
  • Lars Olafsson
    Lars Olafsson over 7 years
    You are a hero! For me i had the mots up to date tzdata, but did a reinstall of the tzdata with "yum reinstall tzdata", and restarted postgres. And now the Django exception was gone! Good timing, was just about to reinstall the whole server, you just saved me a lot of time! Thanks!
  • rahul rachh
    rahul rachh almost 3 years
    It worked for me on windows by installing both: psycopg2==2.8.6 and psycopg2-binary==2.8.6
  • AdjunctProfessorFalcon
    AdjunctProfessorFalcon over 2 years
    This worked for me, bumping around psycopg2 versions isn't helping (using Django 2.1.3)
  • benzkji
    benzkji over 2 years
    2021 solution AHOI
  • Taylor D. Edmiston
    Taylor D. Edmiston over 2 years
    saving you the click on the now closed issue: "tl; dr: if you are using Django 2.2 you must use psycopg < 2.9 in your requirements file."
  • spyker77
    spyker77 over 2 years
    Seems like this issue is mostly related to Django 2.2, and here is the link to the GitHub ticket.