
Introduction
After you have developed and tested your Django application, your next step will be to make your application live and available for your users. There are various platforms through which you can deploy your application. But in this tutorial, I will focus on deploying your Django application using the Heroku platform.
Heroku is a cloud application platform that provides hosting services for multiple programming languages, including Python. It is a Platform-as-a-Service (PaaS) cloud infrastructure. You can read more about Heroku here. Of course, you need an account to get started, so sign up here.
Audience
This post targets existing Python/Django developers and assumes you have a basic understanding of Python, Django, and Virtual Environment. You can follow along. However, you may want to pause here and quickly dive into Python and Django.
Prerequisites
- Before deploying the Django application using Heroku, you should set up a virtual environment for your Django project. Also, make sure to activate the virtual environment.
- As we discussed earlier, you need an account to get started, so sign up here.
- The last prerequisite is the Heroku CLI. Click here to install it for your required operating system.
Preparing The App for Deployment
Before deploying the app we just built to Heroku, we need to add a few configuration files and install some packages to run our app in the production environment.
- pip freeze: This command is used to show all the installed files. Likewise, pip freeze > requirements.txt copies the name of all the files to a text file named requirements.txt.
Run:pip freeze > requirements.txt - Procfile: Add a Procfile in the project root directory to define process types and explicitly declare what command should be executed to start your app.
echo "web: gunicorn PROJECT_NAME.wsgi" > Procfile - Runtime: Now you have to create a runtime.txt file on your root directory (just like the Procfile) and add the python version you’re using. To check which python version you're using, run:
-
python3 --version # output Python 3.9.7 -
Now run:
echo "python-3.9.7" > runtime.txt
Dependencies
You will need to install the following dependencies.
- gunicorn (an application server)
- whitenoise (for serving static files)
- psycopg2-binary (for postgres database)
Install them and update your requirements.txt file:
pip3 install gunicorn whitenoise psycopg2-binary
pip freeze > requirements.txtDjango Settings File
Update your settings file to the following:
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
# ...
]
ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost,*").split(",")
DEBUG = False
MIDDLEWARE = [
# This is the default Django Security Middleware
'django.middleware.security.SecurityMiddleware',
# Add whitenoise middleware here
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
STATICFILES_DIRS = [
BASE_DIR / "static",
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = os.path.join(BASE_DIR, 'media/')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = 'static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.' + os.environ.get('DBENGINE', 'sqlite3'),
'NAME': os.environ.get('DBNAME', BASE_DIR / 'db.sqlite3'),
'USER': os.environ.get('DBUSER', ''),
'PASSWORD': os.environ.get('DBPASSWORD', ''),
'HOST': os.environ.get('DBHOST', '127.0.0.1'),
'PORT': os.environ.get('DBPORT', '3306'),
'OPTIONS': json.loads(
os.getenv('DATABASE_OPTIONS', '{}')
),
}
}
# Email configuration
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = os.environ.get("EMAIL_HOST", "smtp.gmail.com")
EMAIL_USE_TLS = os.environ.get("EMAIL_USE_TLS", True)
EMAIL_PORT = os.environ.get("EMAIL_PORT", 587)
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", 'dummy@ktechhub.com')
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", '')
EMAIL_USE_SSL = False
DEFAULT_FROM_EMAIL = EMAIL_HOST_USERHeroku Deployment
Login to Heroku
heroku loginCreate Heroku project
heroku create PROJECT_NAMECheck the remote repo status
git remote -v
# output
herokuhttps://git.heroku.com/PROJECT_NAME.git (fetch)
herokuhttps://git.heroku.com/PROJECT_NAME.git (push)
origingit@github.com:ktechhub/PROJECT_NAME.git (fetch)
origingit@github.com:ktechhub/PROJECT_NAME.git (push)
Commit and push to Heroku
git add -A
git commit -am "commit message"
git push heroku branch_nameConfigure the Database
To add the Postgres add-on, you have to run
heroku addons:create heroku-postgresql:hobby-dev --app PROJECT_NAMECheck Postgres credentials by running:
heroku pg:credentials:urlThis will display all the database credentials.
Environment Variables
Add the environment variables to the Heroku config. You can always add or update them on Heroku UI or via the cli. We will use the CLI to add them. Update the database credentials with the above output.
heroku config:add DEBUG=False
heroku config:add DISABLE_COLLECTSTATIC=1
heroku config:add SECRET_KEY=jhskfjgsdjgldshkg
heroku config:add DBENGINE=postgresql_psycopg2
heroku config:add DBNAME=dbname
heroku config:add DBHOST=dbhost
heroku config:add DBPASSWORD=password
heroku config:add DBPORT=5432
heroku config:add DBUSER=username
heroku config:add DJANGO_ALLOWED_HOSTS=PROJECT_NAME.herokuapp.com,127.0.0.1,localhostMigrations, Migrate and CreateSuperUser
heroku run python manage.py makemigrations
heroku run python manage.py migrate
heroku run python manage.py createsuperuserVisit your app
https://PROJECT_NAME.herokuapp.com/

Experienced DevOps Engineer proficient in Python, Docker, Kubernetes, CI/CD, and cloud technologies. Specialized in automating processes and building scalable infrastructure for seamless development and deployment.


