I'm learning Docker and after few time, I'm able to run a postgres database and a django app in two different container. The problem is that with docker, I can't use Pycharm's debugging tools.
So I would like to run my code without docker but keep the database in its container.
But I can't connect Dockerized postgres dabatase and locally hosted Django App. I always have this error :
psycopg2.OperationalError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run
self.check_migrations()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\base.py", line 486, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__
self.build_graph()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations
if self.has_table():
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
return self._cursor()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor
self.ensure_connection()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
self.connect()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
self.connect()
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\psycopg2\__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError
I know that professional version of Pycharm allow to connect debugging tool to a docker container but I don't have it.
I saw this question which does the opposite, but I found nothing for my problem.
Here is how my database container is created in docker-compose.yml (authentication data are used only for local dev):
version: "3.7"
services:
db:
container_name: customer_platform_database_local
image: postgres
volumes:
- postgresPFC:/var/lib/postgresql/data
environment:
- POSTGRES_DB=pfcdb
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
hostname: db
expose:
- "5433" # Publishes 5433 to other containers but NOT to host machine
ports:
- "5433:5433"
command: -p 5433
restart: always
...
volumes:
postgresPFC:
And there is my database's settings in settings.py :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'pfcdb',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': 5433,
}
}
I tried to replace the HOST parameter by 127.0.0.1, 172.23.0.1 (which was the db container ip, given with docker inspect), but none of them worked (if I use 172.23.0.1 I have a timeout)
I have the same problem to connect local pgadmin 4 to the containerized databse but I expect it to be solved by the same way.
You can simplify the mapping port on docker-compose.yml, remapping the 5432 to 5433 to host.
With this configuration I'm able to connect to pfcd database with dbeaver
version: "3.7"
services:
db:
container_name: customer_platform_database_local
image: postgres
volumes:
- postgresPFC:/var/lib/postgresql/data
environment:
- POSTGRES_DB=pfcdb
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
hostname: db
ports:
- 5433:5432
restart: always
volumes:
postgresPFC:
For the connection error I suspect the error is on the driver name
not django.db.backends.postgresql but django.db.backends.postgresql_psycopg2 notice the final psycopg2
See this article and the official django host docs
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'pfcdb',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': 5433,
}
}
You must also check if you have another service or Postgres instance running on your host on the same port 5433.
Related
I'm setting up an Amazon AWS test server with Django on which I use Postgres as a database. This was my way here:
$ sudo apt update
$ sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib
I downloaded my files from Github and created a virtual environment for it and inside I installed psycopg2.
$ pip install psycopg2
How I configured Postgres:
$ sudo -i -u postgres
$ psql
$ createuser --interactive (super user);
$ createdb Filme;
Some other information that may be useful about Postgres:
$ service postgresql status
> postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset:>
Active: active (exited) since Wed 2022-10-05 17:08:25 UTC; 20h ago
Main PID: 977 (code=exited, status=0/SUCCESS)
CPU: 1ms
Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Starting PostgreSQL RDBMS...
Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Finished PostgreSQL RDBMS.
$ pg_lsclusters
> Ver Cluster Port Status Owner Data directory Log file
14 main 5432 online postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log
In my settings.py file of my project:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'Filme',
}
}
The error occurs when I try to run the migration to the new database:
$ (env) $ python3 manage.py migrate
> Traceback (most recent call last):
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
self.connect()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
self.connection = self.get_new_connection(conn_params)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
connection = Database.connect(**conn_params)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "ubuntu" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ubuntu/Filmes/manage.py", line 22, in <module>
main()
File "/home/ubuntu/Filmes/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 114, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__
self.build_graph()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations
if self.has_table():
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table
with self.connection.cursor() as cursor:
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor
return self._cursor()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor
self.ensure_connection()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection
with self.wrap_database_errors:
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
self.connect()
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
self.connection = self.get_new_connection(conn_params)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
connection = Database.connect(**conn_params)
File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "ubuntu" does not exist
PS: I also followed the DigitalOcean tutorial, but I end up falling into an almost identical error. (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04)
You've only configured the ENGINE and NAME settings. You have left all the other DB connection settings as default, such as the username, password, etc. So it is trying to connect to the database using the username of the current Linux user, which appears to be ubuntu. I'm guessing when you ran createuser you didn't specify a username of ubuntu and you didn't leave the password blank, so you need to set those settings in the Django database config.
Look at all those database connection settings in the Digital Ocean tutorial you linked, compared to the two settings you have configured in your settings file.
Note that since you are just running Django and Postgres on the same server, there is nothing AWS specific about your issue. It is the same as how you would configure Django/PostgreSQL on any other Linux server. If you are searching for "django connect to postgres on AWS" or something like that, (focusing on the AWS aspect of your problem, when in actuality there is no AWS aspect to your problem at all), that is probably preventing you from finding answers to your question.
I have a Django project that I'm trying to dockerize. I successfully added Django with gunicorn and nginx to Docker. However, when trying to add PostgreSQL, I encountered an issue. My Postgres container starts, but my gunicorn one doesn't start anymore, and I get this error in the logs, so it indeed seems like it comes from Postgres :
C:\Users\stephane.bernardelli>docker logs testapp-django_gunicorn-1
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/manage.py", line 22, in <module>
main()
File "/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 91, in handle
self.check(databases=[database])
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check
all_issues = checks.run_checks(
File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/usr/local/lib/python3.10/site-packages/django/core/checks/model_checks.py", line 36, in check_all_models
errors.extend(model.check(**kwargs))
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1461, in check
*cls._check_indexes(databases),
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1864, in _check_indexes
connection.features.supports_covering_indexes
File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/features.py", line 84, in is_postgresql_11
return self.connection.pg_version >= 110000
File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 354, in pg_version
with self.temporary_connection():
File "/usr/local/lib/python3.10/contextlib.py", line 135, in __enter__
return next(self.gen)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 639, in temporary_connection
with self.cursor() as cursor:
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 284, in cursor
return self._cursor()
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 260, in _cursor
self.ensure_connection()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 243, in ensure_connection
with self.wrap_database_errors:
File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
self.connect()
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
I tried changing the host IP address of postgres in my settings, but it only changed the error, but didn't solve it.
Here is my docker-compose.yml:
version: '3.8'
services:
rabbitmq3:
image: rabbitmq:3-alpine
ports:
- 5672:5672
networks:
- main
postgres:
container_name: postgres
hostname: postgres
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=Scripts Application
networks:
- main
ports:
- "5432:5432"
restart: on-failure
volumes:
- postgresql-data:/var/lib/postgresql/data
django_gunicorn:
volumes:
- static:/static
- media:/media
env_file:
- env
build:
context: .
ports:
- "8000:8000"
command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000"
depends_on:
- postgres
networks:
- main
nginx:
build: ./nginx
volumes:
- static:/static
- media:/media
ports:
- "80:80"
depends_on:
- django_gunicorn
networks:
- main
celery:
restart: always
build:
context: .
command: celery -A main worker -P eventlet -c 100 -l INFO
env_file:
- env
depends_on:
- rabbitmq3
- django_gunicorn
- postgres
networks:
- main
networks:
main:
volumes:
postgresql-data:
static:
media:
Dockerfile:
FROM python:3.10.5-alpine
ENV PYTHONUNBEFFERED = 1
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN \
apk add --no-cache postgresql-libs && \
apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \
python3 -m pip install -r requirements.txt --no-cache-dir && \
apk --purge del .build-deps
COPY ./src /app
WORKDIR /app
I have absolutely no idea where the problem could be coming from, so I'd be glad if someone could guide me on how to solve it, thank you in advance !
I am a newbie developing a Django site in a pipenv virtual environment. The server has been starting and working with no problems. After my computer froze and I restarted with a hard reboot, I can't get the Django server to work.
Here is the error I see after running, python manage.py runserver
((site1) ) userone#theusers-MBP site1 % python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check_migrations()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/core/management/base.py", line 459, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django_tenants/postgresql_backend/base.py", line 122, in _cursor
cursor = super()._cursor()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
Seems that after reboot you do not have postgres running. Can you try logging into pgadmin? Usually it gets installed with postgres default settings.
So go to your windows -start menu - programs - pgadmin.
See if you can connect from there so we can make sure that you have Postgres running before investigating further. Let me know how it goes.
First confirm that the default port for postgres is mentioned as 5432 in the settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydatabase',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '5432',
}
}
Next, start the Postgres by calling:
# Linux
sudo systemctl start PostgreSQL
# Macos
brew services start postgresql
I am a newbie trying to follow this tutorial. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#postgres
I succeeded in building the docker containers but got this error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres".
My question is why has authentication failed when the python and postgres containers env shows the correct user and password? And how can I solve the problem?
I also tried poking around to find pg_hba.conf (because previous answers suggested editing it) but /etc/postgresql does not seem to exist for me.
This is from my python container.
# python
Python 3.8.2 (default, Apr 23 2020, 14:32:57)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ.get("SQL_ENGINE")
'django.db.backends.postgresql'
>>> os.environ.get("SQL_DATABASE")
'postgres'
>>> os.environ.get("SQL_USER")
'postgres'
>>> os.environ.get("SQL_PASSWORD")
'password123'
>>> os.environ.get("SQL_HOST")
'db'
>>> os.environ.get("SQL_PORT")
'5432'
This is from my postgres container.
/ # env
HOSTNAME=6715b7624eba
SHLVL=1
HOME=/root
PG_VERSION=13.2
TERM=xterm
POSTGRES_PASSWORD=password123
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
POSTGRES_USER=postgres
LANG=en_US.utf8
PG_MAJOR=13
PG_SHA256=5fd7fcd08db86f5b2aed28fcfaf9ae0aca8e9428561ac547764c2a2b0f41adfc
PWD=/
POSTGRES_DB=postgres
PGDATA=/var/lib/postgresql/data
/ # ls
bin lib root tmp
dev media run usr
docker-entrypoint-initdb.d mnt sbin var
etc opt srv
home proc sys
/ # cd etc
/etc # ls
alpine-release fstab hosts issue modules-load.d opt periodic resolv.conf shadow- sysctl.d
apk group init.d logrotate.d motd os-release profile securetty shells terminfo
conf.d group- inittab modprobe.d mtab passwd profile.d services ssl udhcpd.conf
crontabs hostname inputrc modules network passwd- protocols shadow sysctl.conf
/etc #
Traceback
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: password authentication failed for user "postgres"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check_migrations()
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 459, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: password authentication failed for user "postgres"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check_migrations()
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 459, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
Dockerfile
FROM python:3.8.2-slim-buster
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \
build-essential \
libpq-dev \
libmariadbclient-dev \
libjpeg62-turbo-dev \
zlib1g-dev \
libwebp-dev \
postgresql-server-dev-all gcc python3-dev musl-dev \
&& rm -rf /var/lib/apt/lists/*
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
# Copy project
COPY . /code/
docker-compose.yml
version: "3.8"
services:
web:
build: .
command: python /code/manage.py runserver 0.0.0.0:8000 #--settings=blog.settings.dev
volumes:
- .:/code
ports:
- 8000:8000
env_file:
- .env/.dev
depends_on:
- db
db:
image: postgres:13.2-alpine
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data/
ports:
- 5432:5432
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password123
- POSTGRES_DB=postgres
volumes:
postgres_data:
# settings.py
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', default=False)
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'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',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE"),
"NAME": os.environ.get("SQL_DATABASE"),
"USER": os.environ.get("SQL_USER"),
"PASSWORD": os.environ.get("SQL_PASSWORD"),
"HOST": os.environ.get("SQL_HOST"),
"PORT": os.environ.get("SQL_PORT"),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
postgres container log
PostgreSQL Database directory appears to contain a database; Skipping initialization
2021-04-27 00:26:40.132 UTC [1] LOG: starting PostgreSQL 13.2 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
2021-04-27 00:26:40.132 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
2021-04-27 00:26:40.132 UTC [1] LOG: listening on IPv6 address "::", port 5432
2021-04-27 00:26:40.143 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2021-04-27 00:26:40.153 UTC [21] LOG: database system was shut down at 2021-04-27 00:26:19 UTC
2021-04-27 00:26:40.158 UTC [1] LOG: database system is ready to accept connections
2021-04-27 00:26:43.454 UTC [28] FATAL: password authentication failed for user "postgres"
2021-04-27 00:26:43.454 UTC [28] DETAIL: Role "postgres" does not exist.
Connection matched pg_hba.conf line 99: "host all all all md5"
.env/.dev
DEBUG=True
SECRET_KEY=7k(&%q+lz33$*0g2i8zc5pn7k4iu7kc+635yz-%f=-=3%kqi$c
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
SQL_ENGINE=django.db.backends.postgresql
SQL_DATABASE=postgres
SQL_USER=postgres
SQL_PASSWORD=password123
SQL_HOST=db
SQL_PORT=5432
D:\blog>docker version
Client: Docker Engine - Community
Cloud integration: 1.0.12
Version: 20.10.5
API version: 1.41
Go version: go1.13.15
Git commit: 55c4c88
Built: Tue Mar 2 20:14:53 2021
OS/Arch: windows/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.5
API version: 1.41 (minimum version 1.12)
Go version: go1.13.15
Git commit: 363e9a8
Built: Tue Mar 2 20:15:47 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.4
GitCommit: 05f951a3781f4f2c1911b05e61c160e9c30eaa8e
runc:
Version: 1.0.0-rc93
GitCommit: 12644e614e25b05da6fd08a38ffa0cfe1903fdec
docker-init:
Version: 0.19.0
GitCommit: de40ad0
Sometimes when setting postgres up in a docker container, you can set the password incorrectly and these incorrect settings will persist. When I get this error, the first thing I always try is to destroy the volume and recreate it.
Use the -v to do this, like so:
docker-compose down -v
Then bring it up again.
This directly relates with docker restart policy. As per your configuration, restart: always, always restart the container if it stops. This may create a distortion on the correct order of your containers. I suggest to remove this particular line(It worked for my case).
I am still not sure why this happened but there is no problem when I run this on my new computer with ubuntu 21.04. I cannot access my previous computer with windows installed so I am going to mark this as closed. Thanks to everyone who tried to help:)
We recently pushed our site to staging and have been struggling to get it up ever since, and the team at Heroku are not really responding in time, so I am turning to the community to see if there is a quick fix.
We scrapped the old one and set up a new stack still with the same issues
heroku config
DISABLE_INJECTION: 1
settings.py
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'PORT': '',
'HOST': 'localhost'
},
}
Here is the full trace.
heroku run python myapp/manage.py syncdb
Traceback (most recent call last):
File "fundedbyme/manage.py", line 11, in <module>
execute_manager(settings)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/app/.heroku/venv/lib/python2.7/site-packages/south/management/commands/syncdb.py", line 90, in handle_noargs
syncdb.Command().execute(**options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 56, in handle_noargs
cursor = connection.cursor()
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/__init__.py", line 252, in cursor
cursor = util.CursorWrapper(self._cursor(), self)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 140, in _cursor
self.connection = Database.connect(**conn_params)
File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?
DATABASES = {
'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))
}
Make sure you have Postgres on your heroku:
heroku addons:add heroku-postgresql:dev
Figure out database url env variable. It's going to look something like this : HEROKU_POSTGRESQL__URL
heroku config | grep POSTGRESQL
Update your settings
import dj_database_url
import os
POSTGRES_URL = "HEROKU_POSTGRESQL_<COLOR>_URL"
DATABASES = {'default': dj_database_url.config(default=os.environ[POSTGRES_URL])}
Bob is your uncle.
I put together a handy bootstrap for django on heroku. It might be helpful: https://github.com/callmephilip/django-heroku-bootstrap
Happy deploying
Try this:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://myuser:mypassword#localhost:5432/mydb')}