DEV Community

Cover image for Deploying Django(3.1) on Heroku

Deploying Django(3.1) on Heroku

fazledyn profile image Ataf Fazledin Ahamed Updated on ・2 min read

In August 4, 2020 Django released it's version 3.1. However, as a beginner Django developer, I faced some issues deploying it to Heroku.

In this post, I will be writing how to deploy it without much hassle that I've faced.

Let's Start

Go to Django project’s file.

Add this
os.environ["DJANGO_SETTINGS_MODULE"] = "<PROJ_NAME>.settings" instead of os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<PROJ_NAME>.settings')

Procfile (As usual)

Add extra attributes (--log-file -) to generate logs
web: gunicorn <PROJ_NAME>.wsgi --log-file -

Everytime you use gunicorn to deploy Django, you are sure to face problems. And using this syntax helps debugging it.

Collect Static (Should I disable?)


Do not, I repeat do not disable collect static method by setting environment variable DISABLE_COLLECTSTATIC to 1

Your own static files will be loaded with no problems but Django packages and modules that have their own static files won't be able to load properly.


Make sure to add a runtime.txt file so that Heroku Dyno knows which Python version to use. With the new Python 3.8, it's now even more important as Heroku Free Dynos usually use older Python versions.


In the newest version of Django(3.1), the file configures the DATABASE dictionary NAME in the following way:

'NAME': BASE_DIR/'db.sqlite3'

As I said, Heroku Dynos won't be able to identify it as string and the build will fail. Thus, we will use it the old and better way, with .join() method:

'NAME': os.path.join(BASE_DIR, 'db.sqlite3') (Constant Variables)

Be sure to declare MEDIA_URL, MEDIA_ROOT, STATIC_URL, STATIC_ROOT, STATICFILE_DIRS constants in the following way:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Enter fullscreen mode Exit fullscreen mode

Production Configuration

Add production configuration in like this:

if os.getcwd() == '/app':
    import dj_database_url
    db_from_env = dj_database_url.config(conn_max_age=500)

    ALLOWED_HOSTS = ['']
    DEBUG = True
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Enter fullscreen mode Exit fullscreen mode

That's all I thought of sharing with you. Kindly let me know if there's anything wrong. I will be pleased to learn.

Discussion (2)

3ng7n33r profile image
Maximilian Blacher • Edited

Hey, thanks for the help, very useful.
However, I had a problem with the last line in the production configuration as it's missing the underscores before "file". It should be:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(_file_)))

fazledyn profile image
Ataf Fazledin Ahamed Author

Glad to help! Thanks for the correction :D

Forem Open with the Forem app