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.
Go to Django project’s wsgi.py file.
os.environ["DJANGO_SETTINGS_MODULE"] = "<PROJ_NAME>.settings" instead of
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.
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.
MOST IMPORTANT PART
In the newest version of Django(3.1), the settings.py file configures the
NAME in the following way:
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
'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
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') STATICFILE_DIRS = [ "static/images", "static/css", "staticfiles",] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Add production configuration in settings.py like this:
if os.getcwd() == '/app': import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['APP_NAME.herokuapp.com'] DEBUG = True BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
That's all I thought of sharing with you. Kindly let me know if there's anything wrong. I will be pleased to learn.