r/django • u/ComfortableSolid4364 • 9h ago
r/django • u/john_uppcoder • 1h ago
Getting a Django + PostgreSQL app online: the two settings that bite behind an HTTPS proxy (and a free way to try it)
I wrote up a step-by-step guide for putting a Django app online with PostgreSQL, and two settings came up that catch a lot of people the first time, wherever they deploy:
1. CSRF_TRUSTED_ORIGINS. Since Django 4.0, a login form posted over HTTPS behind a proxy fails with "403 CSRF verification failed - Origin checking failed" unless your site's address is in CSRF_TRUSTED_ORIGINS. The admin login is usually where you first see it. Reading it from the environment keeps it out of your code:
CSRF_TRUSTED_ORIGINS = [os.environ['APP_URL']] if os.environ.get('APP_URL') else []
2. DATABASES from the environment. startproject gives you SQLite. Pointing it at PostgreSQL with the values your host provides, instead of a password in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': os.environ['POSTGRES_HOST'],
'PORT': os.environ.get('POSTGRES_PORT', '5432'),
}
}
Plus psycopg in your dependencies, then migrate, and createsuperuser --noinput reads DJANGO_SUPERUSER_USERNAME / PASSWORD / EMAIL if you want the admin user created without a prompt.
The full guide, with screenshots of every step, runs it on Uppcoder's free plan, where the app gets its own HTTPS address and VS Code in the browser, and the two settings above are done for you: https://portal.uppcoder.com/guides/deploy-django-postgresql
Disclosure: I work on Uppcoder. Happy to answer questions about any of the steps, on Uppcoder or anywhere else.