How to fix Postgresql connection (cursor) errors when using connection pooling (e.g. with Azure Database for Postgresql)

When using Postgresql as the database with a django app, and connection pooling enabled with e.g. PGBouncer, by default you might run into the following error, seemingly at random every couple of requests:

InterfaceError: connection already closed

with some error message or traceback mentioning failing to create a "cursor".

This happened to us after starting to use a more recent version of Azure Datbase for Postgresql Flexible Server, which has connection pooling enabled by default (which is a great feature!).

It turns out this is mentioned in the Django documentation at https://docs.djangoproject.com/en/4.2/ref/databases/#transaction-pooling-and-server-side-cursors

Using a connection pooler in transaction pooling mode (e.g. PgBouncer) requires disabling server-side cursors for that connection.

So the solution is simply to add the database option "DISABLE_SERVER_SIDE_CURSORS" : True to your Django database connection settings.

See https://docs.djangoproject.com/en/4.2/ref/settings/#disable-server-side-cursors

I am surprised I have not found much about this online, so here it is, I hope it helps other people.