Heroku django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

395 views Asked by At

I am trying to run a django command on my heroku production server, but get the following error:

enter image description here

Note: The same command works fine in my local dev environment.

I took the following steps:

  1. ssh onto my django server:

    heroku ps:exec -a library-backend

  2. I run my custom command:

    python manage.py test_command

  3. Receive error above

My environment variables are set in my settings.py as follows:

import environ

# Setting environment variables
env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env()
DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
DATABASE_URL = env('DATABASE_URL')

My django app runs normally on the heroku server. I am only getting this error when I try to run a custom django management command.

Can anyone see where I'm going wrong?

For reference, the management command is specified in library/management/commands/test_command.py:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def handle(self, *args, **options):
      print("Testing management command")
2

There are 2 answers

1
Andrew Einhorn On

Ok, so I figured this out at last with a hint in the right direction from the comment. When you run:

heroku ps:exec -a <myapp>

Heroku will give you an ssh session with access to the files and folders, but won't set any of your environment variables (like SECRET_KEY or DATABASE_URL)

To get an ssh session with environment variables set, instead used:

heroku run bash -a <myapp>

Now you can run your django command and you won't get any ImproperlyConfigured errors.

0
Austin Burke On

According to the documentation around heroku ps:exec:

The SSH session created by Heroku Exec will not have the config vars set as environment variables (i.e., env in a session will not list config vars set by heroku config:set).