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:
- Django
- Postgres installed
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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line providing more flexibility. HTML adds Structure to a web page, CSS st
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook created React. Developers with a Javascript background can easily develop web applications
15+ min read