Issues with Django and PostgresSQL database

Hello!

I’m trying to migrate after making changes to my database settings because I’m trying to use PostgresSQL. When migrating, an error occur I’ve spend a few hours searching for a solution. Could someone please explain why this error occurs and how I resolve it?

> (my-portfolio-project) C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project>python manage.py migrate
> Traceback (most recent call last):
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection
>     self.connect()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect
>     self.connection = self.get_new_connection(conn_params)
>                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection
>     connection = Database.connect(**conn_params)
>                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\psycopg2\__init__.py", line 122, in connect
>     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> psycopg2.OperationalError
> 
> The above exception was the direct cause of the following exception:
> 
> Traceback (most recent call last):
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\manage.py", line 22, in <module>
>     main()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\manage.py", line 18, in main
>     execute_from_command_line(sys.argv)
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
>     utility.execute()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\__init__.py", line 440, in execute
>     self.fetch_command(subcommand).run_from_argv(self.argv)
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
>     self.execute(*args, **cmd_options)
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\base.py", line 448, in execute
>     output = self.handle(*args, **options)
>              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\base.py", line 96, in wrapped
>     res = handle_func(*args, **kwargs)
>           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle
>     executor = MigrationExecutor(connection, self.migration_progress_callback)
>                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
>     self.loader = MigrationLoader(self.connection)
>                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\migrations\loader.py", line 58, in __init__
>     self.build_graph()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph
>     self.applied_migrations = recorder.applied_migrations()
>                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations
>     if self.has_table():
>        ^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table
>     with self.connection.cursor() as cursor:
>          ^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 323, in cursor
>     return self._cursor()
>            ^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 299, in _cursor
>     self.ensure_connection()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 281, in ensure_connection
>     with self.wrap_database_errors:
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\utils.py", line 91, in __exit__
>     raise dj_exc_value.with_traceback(traceback) from exc_value
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection
>     self.connect()
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect
>     self.connection = self.get_new_connection(conn_params)
>                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
>     return func(*args, **kwargs)
>            ^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection
>     connection = Database.connect(**conn_params)
>                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File "C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project\Lib\site-packages\psycopg2\__init__.py", line 122, in connect
>     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
>            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> django.db.utils.OperationalError
> 
> (my-portfolio-project) C:\Users\abbas\OneDrive\Desktop\vir-envs\my-portfolio-project>

My settings are as follow:

> from pathlib import Path
> import os
> import django_heroku
> import environ
> import dj_database_url
> # from decouple import config
> 
> BASE_DIR = Path(__file__).resolve().parent.parent
> 
> env = environ.Env()
> environ.Env.read_env()
> 
> # Build paths inside the project like this: BASE_DIR / 'subdir'.
> 
> 
> SECRET_KEY = env("SECRET_KEY")
> 
> # HTTPS settings
> SESSION_COOKIE_SECURE = True
> CSRF_COOKIE_SECURE = True
> SECURE_SSL_REDIRECT = True
> 
> # HSTS settings
> 
> SECURE_HSTS_SECONDS = 31536000  # 1 year
> SECURE_HSTS_PRELOAD = True
> SECURE_HSTS_INCLUDE_SUBDOMAINS = True
> 
> # SECURITY WARNING: don't run with debug turned on in production!
> DEBUG = env("DEBUG")  # Must be set to False during production
> 
> # Specify a list of allowed hosts in the ALLOWED_HOSTS setting. This helps prevent HTTP Host header attacks.
> ALLOWED_HOSTS = ["abbasportfolio.herokuapp.com"]
> 
> 
> # Application definition
> 
> INSTALLED_APPS = [
>     'django.contrib.admin',
>     'django.contrib.auth',
>     'django.contrib.contenttypes',
>     'django.contrib.sessions',
>     'django.contrib.messages',
>     'django.contrib.staticfiles',
>     'portfolio_app.apps.PortfolioAppConfig',
> ]
> 
> 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',
>     'whitenoise.middleware.WhiteNoiseMiddleware'
> ]
> 
> ROOT_URLCONF = 'my_portfolio_project.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 = 'my_portfolio_project.wsgi.application'
> 
> 
> # Database
> # https://docs.djangoproject.com/en/4.1/ref/settings/#databases
> 
> DATABASES = {
>     # 'default': {
>     #     'ENGINE': 'django.db.backends.sqlite3',
>     #     'NAME': BASE_DIR / 'db.sqlite3',
>     # }
> 
>     'default': {
>         'ENGINE': 'django.db.backends.postgresql_psycopg2',
>         'NAME': env("DATABASE_NAME"),
>         'USER': env("DATABASE_USER"),
>         'PASSWORD': env("DATABASE_PASSWORD"),
>         'HOST': env("DATABASE_HOST"),
>         'PORT': env("DATABASE_PORT"),
>     }
> }
> 
> 
> # Password validation
> # https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
> 
> LANGUAGE_CODE = 'en-us'
> 
> TIME_ZONE = 'UTC'
> 
> USE_I18N = True
> 
> USE_TZ = True
> 
> 
> # Static files (CSS, JavaScript, Images)
> # https://docs.djangoproject.com/en/4.1/howto/static-files/
> 
> STATIC_URL = '/static/'
> # STATICFILES_DIRS = [BASE_DIR / "static"]
> 
> STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
> # STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
> 
> STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
> 
> # Default primary key field type
> # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
> 
> DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
> 
> django_heroku.settings(locals())

Side note: In the future, when you’re posting code or traceback messages, surround the code (or traceback) between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. Do not prefix each line with the > character. (I’ve made the edit for you this time.)

It’s tough to tell from this, but I’m going to guess that the settings you’re expecting to have in your environment either aren’t there or aren’t set correctly.

Hello!

Absolutely! I’ll do better next time.

I managed to solve it by using the database credentials in Heroku.

Thanks!