Deploying a Django App on Heroku with PostgreSQL
Ohidur Rahman Bappy
MAR 22, 2025
Deploying a Django App on Heroku with PostgreSQL
Learn how to set up a PostgreSQL database and deploy your Django app on Heroku.
Prerequisites
Ensure you have a Heroku account and the Heroku CLI installed. You will also need Python and pip.
Step-by-Step Guide
1. Install PostgreSQL Dependencies
Use pip to install the necessary PostgreSQL adapter:
pip install psycopg2
2. Install Gunicorn
Gunicorn is a Python WSGI HTTP Server for UNIX:
pip install gunicorn
3. Install Heroku CLI
Download and install the Heroku CLI.
4. Login to Heroku via CLI
Authenticate your Heroku account:
heroku login
5. Create Your Heroku App
Replace appname
with your desired app name:
heroku create appname
6. Set Up Your Database
Add a PostgreSQL database to your app:
heroku addons:create heroku-postgresql:hobby-dev --app appname
7. Configure Database URI
Retrieve and add the database URI to your settings.py
:
heroku config --app appname
8. Create a Procfile
In your project root, create a Procfile
:
touch Procfile
Add this line to the Procfile
:
web: gunicorn project_name.wsgi
9. Prepare Dependencies
Generate a requirements.txt
file:
pip freeze > requirements.txt
10. Specify Python Runtime
Create a runtime.txt
to specify the Python version:
python-3.9.1
11. Configure Allowed Hosts
Add your Heroku domain to ALLOWED_HOSTS
in settings.py
:
ALLOWED_HOSTS = ['your_app_name.herokuapp.com']
12. Set Up Static Files
Add STATIC_ROOT
in settings.py
:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
13. Update URL Patterns
Include static URL configurations in urls.py
:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... your URL patterns ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
14. Collect Static Assets
Collect all static files:
python manage.py collectstatic
15. Deploy Using Git
Initialize a Git repository, commit, and push to Heroku:
git init
git add . && git commit -m 'Deploy'
heroku git:remote -a appname
git push heroku master
16. Apply Migrations
Run migrations on the Heroku database:
heroku run bash
python manage.py migrate
python manage.py createsuperuser
17. Monitor Logs
Keep track of your app's logs:
heroku logs --tail
18. Access Your App
Open your deployed app in a browser:
heroku open
This guide should help you successfully deploy your Django application on Heroku with a PostgreSQL database.