DEV Community

Cover image for Environment Variables in Django
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

20 2

Environment Variables in Django

One way of securing your secret keys from external viewers and codebase is to use environment variables.

In Python, you can use the os.getenv('THE_KEY') or os.environ.get('THE_KEY').
For example, when working in Python, you can change tell Django to search for the value of the SECRET_KEY.

SECRET_KEY = os.getenv("SECRET_KEY") 
# or
SECRET_KEY = os.environ.get("SECRET_KEY") 
Enter fullscreen mode Exit fullscreen mode

These lines will lead to software failure if there is no SECRET_KEY variable in the project's .env file.

To avoid that, you can pass as a second argument a default value.

SECRET_KEY = os.getenv(
    "SECRET_KEY", "django-insecure-r(6dd3yaw_05m5kxki1vb^r6v@x^-g#zi_to7487*!)08oxwf)"
)
Enter fullscreen mode Exit fullscreen mode

These methods are quite useful if you are looking to use env vars in Django. Anyway, you can also check django-environ a Python package that allows you to use the Twelve-factor methodology to configure your Django application with environment variables.

Article posted using bloggu.io. Try it for free.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs