Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
How to Deploy Django application on Heroku ?
Next article icon

How to Deploy Django application on Heroku ?

Last Updated : 05 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
How to Deploy Django application on Heroku ?

M

maansi1702
Improve
Article Tags :
  • Python
  • Web Technologies
  • Python Django
  • Heroku Cloud
Practice Tags :
  • python

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 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences