sidx
sidx

Reputation: 640

getting raise KeyError(key) KeyError: 'SECRET_KEY' with django on production settings

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

Upvotes: 14

Views: 33800

Answers (3)

ombima Titus
ombima Titus

Reputation: 1

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"

Upvotes: 0

chank
chank

Reputation: 3636

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

Upvotes: 2

Anshul Goyal
Anshul Goyal

Reputation: 77023

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.

Upvotes: 13

Related Questions