14

I've 2 separate settings files for production and development and a common base.py settings file
base.py

SECRET_KEY = r"!@#$%^&123456"

prod.py

from .base import *
SECRET_KEY = os.environ['SECRET_KEY']

manage.py

#!/usr/bin/env python
import os

import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)

When I enter this in terminal:

python manage.py shell --settings=entri.settings.prod

I get error:

raise KeyError(key)
KeyError: 'SECRET_KEY'

Help me, I'm new to django and python

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
sidx
  • 640
  • 2
  • 11
  • 28
  • 1
    So, where are you setting the SECRET_KEY environment variable? – Daniel Roseman Jan 22 '15 at 13:51
  • I think you are trying this locally, and don't have the SECRET_KEY setup in your environment. Set it using `export SECRET_KEY="somevalue"`, and then this should work fine. – Anshul Goyal Jan 22 '15 at 13:53
  • @mu無 Yes, I'm running this locally. I set the `SECRET_KEY` in **base.py**. That file is imported into **prod.py**. Shouldn't that suffice?? What am I missing? – sidx Jan 22 '15 at 14:43
  • @mu無 Thank you, I figured it out, you were right. Thanks a lot for dumbing it down for me. – sidx Jan 22 '15 at 15:13

3 Answers3

13

I think you are trying this locally, and don't have the SECRET_KEY setup in your environment.

Set it using

export SECRET_KEY="somesecretvalue"

and then running python manage.py shell --settings=entri.settings.prod should work fine.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • Hi, are you able to explain how to set a secret key within the environment, I am having issues with this exact problem and can't figure it out. Thank you – CThomas Dec 04 '19 at 09:29
  • 1
    @CThomas You can ask a fresh question for that with the exact problem you are facing and someone from the community should hopefully answer :) – Anshul Goyal Dec 05 '19 at 06:23
2

I use os.getenv('SECRET_KEY'), instead of os.environ['SECRET_KEY']

print os.getenv('SECRET_KEY')    #returns None if KEY doesn't exist
print os.getenv('SECRET_KEY', 0) #will return 0 if KEY doesn't exist 

my python version is 2.7.12

chank
  • 3,546
  • 1
  • 14
  • 22
0

In Django while trying to secure/hide my secret_key, my problem was even after setting the secret_key using the set command on windows, I still got a 'Key must not be empty' error. I solved that by removing all the spaces before and after the assignment operator in the command. In your cmd, write

set SECRET_KEY="kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"

instead of

set SECRET_KEY = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"