This is the Part 2 of the post Deploying a django app. For Part 1 go here. This part will cover steps required to host your django project on Heroku.

All the files that are created and the shell commands given below should be executed within the root of the project directory i.e. the directory containing the file manage.py
-
Create a Heroku Account here.
-
Download Heroku cli from here.
- Setup git
$ git init $ git status <your-project>/ manage.py ... - Install requirements
$ pip install psycopg2 dj-database-url gunicorn - Create
runtime.txtand write into it the python version of the project (let the version be Python 3.6.4)$ echo "python-3.6.4" > runtime.txt - Create
.gitignoreandProcfile$ echo ".py[cod]" > .gitignore $ echo "web: gunicorn <your_project>.wsgi" > ProcfileReplace
<your_project>with your project name or where the.wsgifile exists. - Login to heroku
$ heroku loginThen enter the credentials.
- Create Heroku Project:
$ heroku create <project_name> - Provision Database Add-on:
$ heroku addons:create heroku-postgresql:hobby-dev - Update
settings.pyto include:DEBUG = False ALLOWED_HOSTS = ['project-name.herokuapp.com', '.yourdomain.com'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # add this import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) DATABASES['default']['CONN_MAX_AGE'] = 500 - Setup Environment Variables
- Go to your app’s Heroku dashboard and navigate to
Settings. - Click on
Reveal Config Vars - Add all the security keys of your project into it. (For example the
SECRET_KEY,EMAIL_HOST_PASSWORDetc.) - Add the key values without any quotes.
- Go to your app’s Heroku dashboard and navigate to
- Update
requirements.txt$ pip freeze > requirements.txt $ git add requirements.txt $ git commit -m "Updated requirements.txt" - Commit & Push
$ git add . $ git commit -m "Initial Heroku commit" $ git push heroku master - Disable Collectstatic in order to use S3 for static files
$ heroku config:set DISABLE_COLLECTSTATIC=1 - Run migrations
$ heroku run python manage.py migrate - Other common commands:
- Create superuser:
heroku run python manage.py createsuperuser - Enter Heroku’s bash:
heroku run bashfor shell access - Live Python-Django shell:
heroku run python manage.py shell
- Create superuser:
Custom Domains & SSL on Heroku
- Add a Custom Domain
$ heroku domains:add <your-custom-domain.com> $ heroku domains:add www.<your-custom-domain.com> -
Update your DNS to what heroku says above
- Enable Heroku to Handle Let’s Encrypt Certificate
$ heroku certs:auto:enable
Note
- When changes are made to the models, run
makemigrationslocally first, then push the changes to heroku and then runmigrateon the production server. (This is because, if any error occurs in models, then we can fix it locally first.) - Whenever some changes are made to the environment variables in herkou, restart the server from
More --> Restart all dynos