3

Here I have used django-environ to set the environment variable but it is giving me SECRET_KEY error.How to properly configure the environmental variable?

I also used the python-decouple for this instead of django-environ which works fine but didn't work with django-environ.

What is the difference between django-environ and python-decouple which will be the best for this ?

settings

import environ
env = environ.Env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)

.env file

DEBUG = True
SECRET_KEY = #qoh86ptbe51lg0o#!v1#h(t+g&!4_v7f!ovsl^58bo)g4hqkq #this is the django gives 

Got this exception while using django-environ

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

shuttle87
  • 15,466
  • 11
  • 77
  • 106
D_P
  • 802
  • 10
  • 32

1 Answers1

4

django-environ works fine, but you need to load the .env file – just instantiating an Env does not do that:

import environ
env = environ.Env()
env.read_env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)

In addition, I've found it an useful idiom to have "sane defaults" based on the DEBUG value (which must only be true when developing):

DEBUG = env.bool("DEBUG", False)
SECRET_KEY = env('SECRET_KEY', default=('insecure' if DEBUG else Env.NOTSET))

Setting Env.NOTSET as the default will have django-environ complain for unset values.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • AttributeError: 'Env' object has no attribute 'load_envfile' it throws this error – D_P Feb 14 '20 at 08:44
  • 3
    is there any particular difference between using `python-decouple` and `django-environ` – D_P Feb 14 '20 at 09:01
  • Decouple seems to support .ini files for some reason too. Django-environ otoh has useful helpers for e.g. database settings. – AKX Feb 14 '20 at 09:03