DEV Community

Discussion on: Django Cheat Sheet: Keep Credentials Secure with Environment Variables

nicolaerario profile image
Nicola Erario

How do you manage Boolean with python-dotenv? I mean that ( for example)DEBUG = True or DEBUG = False in .env file are always evaluated as True

jamestimmins profile image
James Timmins Author

Yeah, that's an unfortunate drawback of dotenv. There's a couple of things you can do.

  1. Explicitly check for a string value. DEBUG = (os.getenv("DEBUG") == 'true')
  2. Cast the val to a boolean DEBUG = bool(os.getenv("DEBUG")), and use an empty string to denote a false value DEBUG=''.
  3. Use a more fully-featured package like django-environ. There's slightly more configuration required, but if your project has multiple boolean settings it might be worth it. (I haven't actually used django-environ, but it looks pretty interesting so I may investigate).
bhupesh profile image
Bhupesh Varshney 👾

thanks for this

anshsaini profile image
Ansh Saini

Okay I'm surprised I didn't know that! Thanks. This'll save me some future headaches.

nicolaerario profile image
Nicola Erario

Sure! After time spent to True this, False that... and your app lives of it’s own life

guettli profile image
Thomas Güttler

Don't ask my why the author did not accept my PR:

Converting types

The library reads and provides strings. If you need for example a boolean, it is up to you to convert the value.


from distutils.util import strtobool
DEBUG = bool(strtobool(os.getenv('DEBUG', 'True')))
Enter fullscreen mode Exit fullscreen mode