How to Deploy Django application on Heroku ?
Last Updated :
05 Sep, 2020
Django is an MVT web framework used to build web applications. It is robust, simple, and helps web developers to write clean, efficient, and powerful code. In this article, we will learn how to deploy a Django project on Heroku in simple steps. For this, a Django project should be ready, visit the following link to prepare one:https://www.geeksforgeeks.org/django-tutorial/
Prerequisites:
Requirements.txt file: Create requirements.txt file in the same directory as your manage.py. Run the following command in the console with the virtual environment activated:
(myvenv) $ pip install dj-database-url gunicorn whitenoise
(myvenv) $ pip freeze > requirements.txt
Check your requirements.txt. It will be updated with the packages currently installed in your project.
Procfile: Create a file named Procfile in the same directory as manage.py. you will see the Heroku logo as Procfile's icon. Add the following line to it:
web: gunicorn <project_name>.wsgi --log-file -
Here project name will be the name of the folder in which your settings.py is present. Procfile explicitly declares what command should be executed to start your app.
Runtime.txt file: Create runtime.txt file in the same directory as your manage.py. Add the python version you want to use for your web app:
python-3.7.1
Settings.py: Modify your settings.py as per the instructions below:
1.Set debug as False.
DEBUG = False
2. Modify allowed hosts.
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
3. To disable Django’s static file handling and allow WhiteNoise to take over add 'nostatic' to the top of your 'INSTALLED_APPS' list.
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
# ...
]
4. Add WhiteNoise to the MIDDLEWARE list. The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
5. Update your database settings.
import dj_database_url
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<database_name>',
'USER': '<user_name>',
'PASSWORD': '<password>',
'HOST': 'localhost',
'PORT': '',
}
}
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
6. To serve files directly from their original locations (usually in STATICFILES_DIRS or app static subdirectories) without needing to be collected into STATIC_ROOT by the collectstatic command; set WHITENOISE_USE_FINDERS to True.
WHITENOISE_USE_FINDERS = True
7. WhiteNoise comes with a storage backend that automatically takes care of compressing your files and creating unique names for each version so they can safely be cached forever. To use it, just add this to your settings.py:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Final modified Contents of settings.py:
import dj_database_url
...
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
#...
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
#...
]
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<database_name>',
'USER': '<username>',
'PASSWORD': '<password>',
'HOST': 'localhost',
'PORT': '',
}
}
WHITENOISE_USE_FINDERS = True
...
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Heroku account
1. Install your Heroku toolbelt which you can find here: https://toolbelt.heroku.com/
2. Authenticate your Heroku account either running the below command in cmd or gitbash
$heroku login
Here the directory of the project(resume) to be deployed is active
Sometimes the cmd or git bash may freeze at certain commands. Just use CTRL+C to come out of it.
3. Commit any changes on git before deploying.
$ git status
$ git add -A .
$ git commit -m "additional files and changes for Heroku"
4. Pick your application name which will be displayed on the domain name-- [your app's name].herokuapp.com and create the application using below command:
$ heroku create <your_app's_name>
5. Debugging: If collectstatic failed during a build, a traceback was provided that will be helpful in diagnosing the problem. If you need additional information about the environment collectstatic was run in, use the DEBUG_COLLECTSTATIC configuration.
$ heroku config:set DEBUG_COLLECTSTATIC=1
6. Disabling Collectstatic: Sometimes, you may not want Heroku to run collectstatic on your behalf. You can disable the collectstatic build step with the DISABLE_COLLECTSTATIC configuration:
$heroku config:set DISABLE_COLLECTSTATIC=1
7. Finally, do a simple git push to deploy our application:
$ git push heroku master
8. When we deployed to Heroku, we created a new database and it's empty. We need to run the migrate and createsuperuser commands.
$ heroku run python manage.py migrate

$ heroku run python manage.py createsuperuser
The command prompt will ask you to choose a username and a password again. These will be your login details on your live website's admin page.
9. To open your site run:
$ heroku open
Resolving Errors
In case you see application error on your website run:
$heroku logs --tail
It displays recent logs and leaves the session open for real-time logs to stream in. By viewing a live stream of logs from your app, you can gain insight into the behavior of your live application and debug current problems. When you are done, press Ctrl+C to return to the prompt.
Similar Reads
How To Deploy a Django Application to Heroku with Git CLI?
Deploying a Django application to Heroku using the Git command-line interface (CLI) is a simple process. Heroku provides a platform-as-a-service (PaaS) that enables you to deploy, manage, and scale your applications easily. This guide will walk you through the steps to deploy your Django application
3 min read
How to Make Changes to The Application Deployed on Heroku ?
Many of the times we need to make changes to our deployed project for some reason. Either we want to have a new version of the project, add new features to the project, remove a bug, or for some other reasons. If your project is deployed on Heroku Cloud Platform, you can easily make your changes usi
2 min read
How to Dockerize a Django Application?
Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers(namespace). To understand this perspective in a detailed way let's do a quick comparison between the virtual machines and containers:Imagine virtualization as a lock t
6 min read
How do you deploy a React application?
Deploying a React application is the process of making your React project accessible on the internet so that users can interact with it. It involves several steps to ensure your application is properly built, uploaded to a hosting service, and configured to work correctly in a live environment. This
2 min read
How to Deploy a Golang WebApp to Heroku?
Go, also known as "Golang," is gaining popularity among DevOps professionals in recent years. There are many tools written in Go, including Docker and Kubernetes, but they can also be used for web applications and APIs. While Golang can perform as fast as a compiled language, coding in it feels more
5 min read
How to deploy React app to Heroku?
React is a very popular and widely used library for building User Interfaces. So if you are thinking about deploying your React app to the cloud platform, there are various choices for doing that such as AWS EC2 or Heroku. But for testing your React app, Heroku will be the best option as it is free
3 min read
Deploy an ASGI Django Application
ASGI, which stands for Asynchronous Server Gateway Interface, is a big deal in Django. It basically helps Django handle lots of things at once, like requests from users. Instead of waiting for one thing to finish before starting the next, ASGI lets Django do multiple tasks simultaneously. It's like
5 min read
How to Run a Flask Application
After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal:flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file.Dem
4 min read
How to Deploy Node.js Express Application on Render ?
Deploying a Node.js Express application on Render is straightforward and involves a few key steps to set up your project, configure deployment settings, and manage your application on the Render platform. Render provides an easy-to-use platform for deploying applications, offering features like auto
4 min read
Deploying Django App on Heroku with Postgres as Backend
Django is a high-level Python web framework used to create web applications without any hassle, whereas, PostgreSQL is a powerful, open-source object-relational database. Let us first create a Django application with PostgreSQL in the backend and deploy it in Heroku which is a container-based cloud
5 min read