Postgresql database not working

Hey, I’m trying to set up my django project following this tutorial (Getting Started · Fly Docs), and it works fine locally, but deploying it gives me the error that ‘ModuleNotFoundError: No module named ‘psycopg2’’ and it keeps looping until it crashes. It also tells me that it’s listening on the wrong port, even though I only tell it to listen on port 8000 in every doc. I’ll share my documents below, tell me if you need to see anything else.

Settings.py:
“”"
Django settings for mysite project.

Generated by ‘django-admin startproject’ using Django 4.1.4.

For more information on this file, see

For the full list of settings and their values, see

“”"

from pathlib import Path
from environs import Env

env = Env()
env.read_env()

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 Deployment checklist | Django documentation | Django

SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = ‘django-insecure-c03xfc_y^u(z%ds-b0ds0&g3sr!gwj1k0bmg#dsca7mn!is4k8’
‘’’
SECRET_KEY = env.str(
“SECRET_KEY”,
default=“gOQawfblQWnGbA0DxfhVg6iiE8HCf3u8MTHr9PmHiXzb85fCsW”,
)
‘’’

SECRET_KEY = django.core.management.utils.get_random_secret_key()

SECURITY WARNING: don’t run with debug turned on in production!

DEBUG = False

#ALLOWED_HOSTS = [‘localhost’, ‘127.0.0.1’, ‘192.168.1.254’]
ALLOWED_HOSTS = ['']
CSRF_TRUSTED_ORIGINS = ["https://
.fly.dev"]

Application definition

INSTALLED_APPS = [
‘daphne’,
‘chat’,
‘core’,
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘whitenoise.runserver_nostatic’,
‘django.contrib.staticfiles’,
]

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘whitenoise.middleware.WhiteNoiseMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
“whitenoise.middleware.WhiteNoiseMiddleware”,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]

ROOT_URLCONF = ‘mysite.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 = ‘mysite.wsgi.application’

Database

Settings | Django documentation | Django

‘’‘DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3’,
‘NAME’: BASE_DIR / ‘db.sqlite3’,
}
}
‘’’

DATABASES = {
“default”: env.dj_db_url(“DATABASE_URL”, default=“sqlite:///db.sqlite3”),
}

Password validation

Settings | Django documentation | Django

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

Internationalization and localization | Django documentation | Django

LANGUAGE_CODE = ‘en-us’

TIME_ZONE = ‘UTC’

USE_I18N = True

USE_TZ = True

Static files (CSS, JavaScript, Images)

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django

STATIC_ROOT = BASE_DIR / ‘staticfiles’
STATIC_URL = ‘static/’
STATICFILES_STORAGE = “whitenoise.storage.CompressedManifestStaticFilesStorage”
LOGIN_REDIRECT_URL = ‘/’
LOGOUT_REDIRECT_URL = ‘/login/’

Default primary key field type

Settings | Django documentation | Django

DEFAULT_AUTO_FIELD = ‘django.db.models.BigAutoField’

ASGI_APPLICATION = “mysite.asgi.application”

CHANNEL_LAYERS = {
“default”: {
“BACKEND”: “channels_redis.core.RedisChannelLayer”,
“CONFIG”: {
“hosts”: [(“127.0.0.1”, 6379)],
},
},
}

Fly.toml:

fly.toml app configuration file generated for discuss-it-muddy-brook-1713 on 2023-12-15T16:05:19-05:00

See Fly Launch configuration (fly.toml) · Fly Docs for information about how to use this file.

app = “discuss-it-muddy-brook-1713”
primary_region = “bos”
console_command = “/code/manage.py shell”

[build]

[env]
PORT = “8000”

[http_service]
internal_port = 8000
force_https = true
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 0
processes = [“app”]

[[vm]]
cpu_kind = “shared”
cpus = 1
memory_mb = 1024

[[statics]]
guest_path = “/code/static”
url_prefix = “/static/”

Dockerfile:

ARG PYTHON_VERSION=3.8-slim-bullseye

FROM python:${PYTHON_VERSION}

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN mkdir -p /code

WORKDIR /code

install psycopg2 dependencies

RUN apt-get update && apt-get install -y
libpq-dev
gcc
&& rm -rf /var/lib/apt/lists/*

COPY requirements.txt /tmp/requirements.txt
RUN set -ex &&
pip install --upgrade pip &&
pip install -r /tmp/requirements.txt &&
rm -rf /root/.cache/
COPY . /code

ENV SECRET_KEY “SbbGscCgguteREwuBz8dHUN2EQNAfoebspUykfftjFSAGwWl0o”
RUN python manage.py collectstatic --noinput

EXPOSE 8000

CMD [“gunicorn”, “–bind”, “:8000”, “–workers”, “2”, “mysite.wsgi”]

Requirements.txt
asgiref==3.6.0

async-timeout==4.0.2

attrs==22.2.0

autobahn==22.12.1

Automat==22.10.0

backports.zoneinfo==0.2.1

cffi==1.15.1

channels==4.0.0

channels-redis==4.0.0

constantly==15.1.0

cryptography==38.0.4

daphne==4.0.0

dj-database-url==2.1.0

Django==4.1.4

django-ipware==5.0.0

django-utils==0.0.2

environs==9.5.0

gunicorn==21.2.0

hyperlink==21.0.0

idna==3.4

incremental==22.10.0

marshmallow==3.20.1

msgpack==1.0.4

packaging==23.2

pyasn1==0.4.8

pyasn1-modules==0.2.8

pycparser==2.21

pyOpenSSL==22.1.0

pyscopg2==66.0.2

python-dotenv==1.0.0

redis==4.4.0

redis-cli==1.0.1

service-identity==21.1.0

six==1.16.0

sqlparse==0.4.3

Twisted==22.10.0

txaio==22.2.1

typing_extensions==4.2.0

tzdata==2022.7

whitenoise==6.5.0

zope.interface==5.5.2

Let me know if you need anything else, any help would be appreciated

I use the requirement psycopg2-binary rather than psycopg2. it comes with all the prerequisites that the environment needs. You may find posts saying to build from source but I have found on a few deployment platforms that it just works as it has all the prerequisites.

Change your requirements and do a redeploy to see if that works :slight_smile:

The official docs advise not to do this:

The binary package is a practical choice for development and testing but in production it is advised to use the package built from sources.

@shugel perhaps it would be better to describe how to build from source for fly.io rather than just stating “don’t do this”. Both @Bookboss11 and I could learn how to do this properly on the platform this way :wink: