Preparing Heroku

What we have so far is a basic Django project. With everything we did so far, we have a decent basis to extend the project by adding a superuser, apps, models, views, templates, etc.

Create a Heroku app

Verify that you are logged in with the correct Heroku user:

Terminal
heroku auth:whoami

Choose a unqiue name and region for your Heroku app.

Then create your Heroku app with the Heroku CLI:

Terminal
# Important: Change {appname} to a unique app name and {region} to your preferred region.
heroku apps:create {appname} --region {region}

Add a new secret key to Heroku

Heroku relies on env variables the same way we did on your local system. Heroku will set the URL to the database itself. But SECRET_KEY must be set by us.

It is a good idea to create a separate SECRET_KEY for each environment.

Let’s create a new one the same way as before.

Start the Django shell in the terminal:

Terminal
python manage.py shell
Terminal
from django.core.management.utils import get_random_secret_key

get_random_secret_key()

Copy the output (e.g. 'NEWLY%G3GENERATEDsecret_KEY!').

Terminal
# Important:
# * Change {appname} to your app name
# * CHange {secretkey} to your secret key
heroku config:set -a {appname} SECRET_KEY={secretkey}
You may also set the DEBUG env variable. The way we configured it in settings.py it defaults to False when not set – which is recommended for the app on Heroku.

Create a Procfile with Gunicorn

All Heroku applications require a Procfile. This file must be located in the root of the project. It declares how Heroku should run your application.

For Django we will tell Heroku to run a Gunicorn server for us.

Create a Procfile:

Terminal
echo web: gunicorn djangoku.wsgi > Procfile
If you named your project differently, you need to adjust the command above accordingly.

Install gunicorn:

Terminal
pip install gunicorn

Expand allowed hosts

Django checks for the HTTP_HOST header of requests. It rejects requests coming from urls that are not part of the ALLOWED_HOSTS list in the settings.

You need to add the url of your Heroku app and any custom domains that you may use for the project.

Add the url of the Heroku app to settings.py:

djangoku/settings.py (Around line 33)
# Important:
# Replace {appname} with your Heroku app name

ALLOWED_HOSTS = [
    "{appname}.herokuapp.com",
]

Update our requirements

Now that we have a new module in our project, let’s update our requirements.

Update requirements.txt:

Terminal
pip freeze > requirements.txt

Commit the code

If you run git status you will see, that we updated requirements.txt and settings.py, and added Procfile.

Now we can stage and commit our changes:

Terminal
git add .
git commit -m "Prepare Heroku app 🔌"

Checklist

✔︎ Heroku app exists

Terminal
heroku apps

→ Your app is part of the Heroku apps list

✔︎ SECRET_KEY is set on Heroku

✔︎ Procfile is present

✔︎ Gunicorn is part of requirements

results matching ""

    No results matching ""