167

I have done server setup multiple times with the same settings but this time, I am seeing the error message. It is not even allowing to migrate the database.

System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check_migrations()
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 212, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
    return {(migration.app, migration.name): migration for migration in self.migration_qs}
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 276, in __iter__
    self._fetch_all()
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1170, in execute_sql
    return list(result)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in cursor_iter
    for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in <lambda>
    for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
  File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/utils.py", line 97, in inner
    return func(*args, **kwargs)
  File "/home/datanal/datanal-samply/venv/lib/python3.9/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

Here is my settings.py for timezone.

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

OS: Ubuntu 21.04 Python Version : 3.9.5 Django Version: 3.0 PostgreSQL: 13.3

I have also gone through another question but did not find any solution. Is there anyone who can help me to get this done? I have multiple server setup with same code without changing anything and worked but this time it is not.

Narendra Vishwakarma
  • 1,790
  • 2
  • 5
  • 7
  • Does this answer your question? [Django 1.9.2 AssertionError: database connection isn't set to UTC](https://stackoverflow.com/questions/38807296/django-1-9-2-assertionerror-database-connection-isnt-set-to-utc) – AKX Jun 17 '21 at 17:34
  • 3
    This did not help me to solve my response. I tried all ways mentioned in this question but my query not resolved. – Narendra Vishwakarma Jun 17 '21 at 17:39
  • 7
    I am facing the exact same problem, and it showed up yesterday. Can you try `USE_TZ = False` in you settings and confirm that it "fixes" the error? BTW I am having this error with Django 2.2.13 and Postgres 11 – Anas Tiour Jun 17 '21 at 18:15
  • 5
    I am facing the same issue, which happened yesterday. setting the `USE_TZ = False` solved it but I really don't know what happened. ```postgres=# select * from pg_timezone_names where name like 'UTC'; name | abbrev | utc_offset | is_dst ------+--------+------------+-------- UTC | UTC | 00:00:00 | f``` – bbambbam sh2ee2 Jun 17 '21 at 18:33

8 Answers8

317

The release of psycopg2 version 2.9 caused this error as explained in this GitHub issue:

https://github.com/psycopg/psycopg2/issues/1293#issuecomment-862835147

Psycopg 2.9 changed the value passed to tzinfo_factory from an int to a timedelta. Django 2.2 (possibly newer but I'm on 2.2) has a check for offset == 0 and since timedelta(0) != 0 it goes boom.

One solution is to downgrade psycopg2 (or psycopg2-binary if you are using the stand-alone package) below 2.9 (e.g. psycopg2>=2.8,<2.9) in your requirements file.

For instance you can downgrade to 2.8.6 using:

pip install psycopg2==2.8.6

or

pip install psycopg2-binary==2.8.6

If you're using poetry, you can do poetry add psycopg2@2.8.6 to fix your version to 2.8.6.

psycopg2 release history

t-payne
  • 3,514
  • 1
  • 6
  • 9
  • 8
    Can confirm this. Problem appeared after upgrading `psycopg2-binary` from 2.8.6 to 2.9. Reverting it resolves it – Anas Tiour Jun 17 '21 at 19:58
  • 7
    Yes,i have just got the same issue,downgrading psycopg2 to 2.8.6 solved it. – mohammed awni Jun 17 '21 at 20:15
  • Current ReviewBoard installation fails for this very problem. – Peter Silon Jul 06 '21 at 10:57
  • 3
    I can confirm that the above solution of downgradding to pip install psycopg2-binary==2.8.6 works, i think psycopg2-binary-2.9.1 has issues that needs to be fixed – Mugoya Dihfahsih Aug 06 '21 at 15:42
  • psycopg 2.8.6 works now very well with django 3.0.1 – alexzander Dec 19 '21 at 17:15
  • Heads up: following the linked question in the first comment I eventually ended up on the matching [psycopg2 issue about the problem which is **Closed**](https://github.com/psycopg/psycopg2/issues/1293) . What the psycopg2 guys had to say was: *TLDR: if you are using Django 2.2 you must use psycopg < 2.9 in your requirements file.* I can understand their point of view, which seems to be that it is an edge case related to an internal/implementation detail **and** can be fixed by updating Django. I greatly appreciate psycopg2 and let's understand it's not going to be "fixed" by psycopg2. – JL Peyret Jan 21 '22 at 20:55
  • 7
    not an option on m1 mac to use 2.8.6.. it will not compile :( – radtek Jan 21 '22 at 23:53
  • Thanks! This solved my issue on GitHub CI (while everything was working fine both locally and locally inside the Docker). – Artur Barseghyan Jun 23 '22 at 20:48
  • 1
    confirmed in mac M2 it's working – Rikudo Pain Sep 14 '22 at 14:19
  • @RikudoPain same situation over here. - downgrading did not work - downgrading to other 2.9.x versions did not work 2.9.6 worked with 3.2.x `django` – ivanculet Aug 04 '23 at 17:05
19

I had the same problem and i fixed it by simply removing this line from my settings.py file

USE_TZ = True
  • 9
    From a quick test, I can confirm that `USE_TZ = False` does indeed fix the psycopg2 (psycopg2==2.9.3) connection issue . However, and that's probably the reason for the downvote, doing so might cause all sorts of other problems with other parts of Django expecting Time zone awareness and would modify the nature of timestamp data (I expect it would, just didn't do any further tests beyond checking the connection worked to *read* data). – JL Peyret Jan 21 '22 at 21:05
15

I solved this by upgrading Django instead of downgrading psycopg. I don't know which version solves the issue exactly, but 3.2 certainly does.

The accepted answer is out of date now and you should decide against downgrading if you have the option to upgrade Django instead.

theberzi
  • 2,142
  • 3
  • 20
  • 34
  • 6
    The accepted answer is **not** out of date, as numerous recent comments on it indicate. Upgrading Django is **not** a trivial task and should be weighed carefully against the temporary workaround of minor downgrading of the psycopg2 version which still works fine as of today, (unless it becomes critical to upgrade psycopg2 for other reasons such as security). – JL Peyret Jan 21 '22 at 20:02
  • It is still useful, but nonetheless out of date for those that can afford upgrading, and presumably psycopg2 will be updated to solve the bug at some point, if it hasn't already (I haven't checked). If to solve a problem you can either upgrade or downgrade, my money will always be on the upgrade. – theberzi Jan 22 '22 at 16:50
  • 1
    The upgrade downgrade are not the same “weight”. One is a utitility function that is getting a feature update (2.8.x to 2.9.x). The other is a full web framework that is going from 2.x to 3.x major release, with known breaking changes. It is **major** work. Had you not made this claim that the accepted answer is bad, you’d have gotten no remark from me, yours is otherwise a good answer. As it is, I’d hate for someone new and impressionable to be pressured into a premature, insufficiently planned, upgrade of Django. – JL Peyret Jan 22 '22 at 21:14
  • I don't necessarily advice to update the major version, 3.2 is simply the one I updated to and so the only one I can confirm works, but an update within the 2.x range might also possibly do the trick. Anyone willing to experiment can do that and update my answer, less adventurous users can take the advice of the other answers and downgrade psycopg if, as I note in my answer, they don't have the option of upgrading. I consider the accepted answer out of date because it frames the downgrade as the *only* solution, which it isn't anymore. – theberzi Jan 23 '22 at 20:06
11

This is what I am working to get this all working on Django 2.2.x (which is not compatible with psycopg2>=2.9.0:

brew install libpq --build-from-source
brew install openssl
brew link openssl
export LDFLAGS="-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/libpq/lib"
export CPPFLAGS="-I/opt/homebrew/opt/openssl@1.1/include -I/opt/homebrew/opt/libpq/include"
echo 'export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"' >> ~/.zshrc
brew install postgres
pip install psycopg2==2.8.6

I am on BigSur on a M1 macbook.

radtek
  • 34,210
  • 11
  • 144
  • 111
2

For ubuntu users, installing psycopg2==2.8.6, psycopg2-binary==2.8.6 with older versions of django may raise some kind of error. To solve that issue, try,

sudo apt-get install gcc libpq-dev -y

sudo apt-get install python3-dev python3-pip python3-venv python3-wheel -y

pip3 install wheel

This is one kind of solution, other solutions are available at the link below. https://exerror.com/error-invalid-command-bdist_wheel/#:%7E:text=Just%20use%20below%20command%20pip,command%20python%20setup.py%20bdist_wheel.&text=invalid%20command%20%27bdist_wheel%27-,To%20Solve%20error%3A%20invalid%20command%20%27bdist_wheel%27%20Error%20You%20just,command%20python%20setup.py%20bdist_wheel.?

  • As mentioned in https://stackoverflow.com/questions/19843945/psycopg-python-h-no-such-file-or-directory one may need to use something like sudo apt-get install python3.10-dev rather than just python3-dev – gmcc051 Oct 23 '22 at 08:11
-1

Ensure you have activated your virtual environment if any case you have deactivated it (please ensure you are within the virtual environment)

to activate your virtual environment use this command: source name of the virtual env/bin/activate

-1

I had this issue..solved by updating django latest version.

INSTALLED_APPS = [
    'cart',
]

this line caused me error when lower version (2.2) is used u can also solve this issue by changing the above line of code to

INSTALLED_APPS = [
        'cart.apps.CartConfig',   
]

CartConfig is the class name u can copy and paste from apps.py of the same app

helvete
  • 2,455
  • 13
  • 33
  • 37
-1

Author Admin,

ubuntu desktop Ubuntu 22.04.3 LTS

Change in setting.py in your django USE_TZ = False, you're indicating that PostgreSQL will handle time zone conversions, so Django won't interfere with it.

my ubuntu setting in pycharm django

Admin
  • 1