0

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")
Andrew Einhorn
  • 741
  • 8
  • 23
  • 1
    How are you connecting to your heroku server? Does this help? https://stackoverflow.com/questions/48119289/how-to-get-environment-variables-in-live-heroku-dyno – Iain Shelvington Aug 28 '21 at 10:21

2 Answers2

0

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).

Austin Burke
  • 148
  • 2
  • 10
-1

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.

Andrew Einhorn
  • 741
  • 8
  • 23
  • `heroku run bash` will spin up a new dyno whereas `heroku ps:exec` will ssh into the running dyno. So this does not solve the problem – Eiri Mar 09 '22 at 11:13