When deploying Django with production services like Gunicorn, it is common practice to keep sensitive settings, like SECRET_KEY, in environment variables instead of settings.py. This can cause issues when running management commands from the terminal, such as collectstatic, because the environment variable may not be available in your shell.

Step 1: Find the SECRET_KEY from your Gunicorn service

If your Django app is running with Gunicorn and the SECRET_KEY is set in the environment, you can retrieve it using one of the following methods depending on your setup:

  • Systemd service: Open the Gunicorn service file (usually /etc/systemd/system/gunicorn.service) and look for Environment="SECRET_KEY=..." or an EnvironmentFile that contains it.
  • Docker: If your app runs in Docker, check the container environment variables:
    docker exec -it <container_name> env | grep SECRET_KEY
  • Manual export: If Gunicorn was started manually, the variable may have been exported in the shell before starting it:
    export SECRET_KEY='your_secret_key_here'
    gunicorn my_blog.wsgi:application

Step 2: Run Django management commands with the SECRET_KEY

Once you know your SECRET_KEY, you can run management commands by specifying it inline. For example, to run collectstatic:

SECRET_KEY='your_secret_key_here' python my_blog/manage.py collectstatic

This temporarily sets the SECRET_KEY for that command without modifying settings.py. This works for any Django management command, including migrate or createsuperuser.

Step 3: Optional – Make it easier for repeated use

To avoid typing the key every time, you can store it in your shell session or a .env file:

# Add this to ~/.bashrc or ~/.zshrc
export SECRET_KEY='your_secret_key_here'

Or create a .env file in your project and use libraries like python-decouple or django-environ to load it automatically.

Conclusion

By retrieving the SECRET_KEY from your Gunicorn environment and setting it inline when running Django commands, you can safely manage your production application without storing sensitive keys in settings.py.