0
0
Djangoframework~30 mins

Environment variables for secrets in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variables for secrets in Django
📖 Scenario: You are building a Django web application that needs to keep sensitive information like the secret key safe. Instead of writing the secret key directly in the code, you will use environment variables to store and access it securely.
🎯 Goal: Learn how to set up and use environment variables in Django to keep secrets like SECRET_KEY outside your code files.
📋 What You'll Learn
Create a .env file with the secret key
Load environment variables in Django settings
Use the environment variable for SECRET_KEY
Add fallback default for SECRET_KEY
💡 Why This Matters
🌍 Real World
Keeping secret keys and passwords out of code helps protect your app from leaks and makes it easier to change secrets without changing code.
💼 Career
Many companies require secure handling of secrets in web apps. Knowing environment variables is a key skill for Django developers.
Progress0 / 4 steps
1
Create a .env file with the secret key
Create a file named .env in your project root folder. Inside it, write the line SECRET_KEY='django-insecure-12345' exactly as shown.
Django
Need a hint?

The .env file stores environment variables as key=value pairs. Use single quotes around the value.

2
Install and import python-dotenv to load environment variables
In your Django settings.py file, add import os and from dotenv import load_dotenv at the top. Then call load_dotenv() to load variables from the .env file.
Django
Need a hint?

Use pip install python-dotenv before running your project to install the package.

3
Use environment variable for SECRET_KEY in settings.py
Replace the existing SECRET_KEY assignment in settings.py with SECRET_KEY = os.getenv('SECRET_KEY') to get the secret key from the environment variable.
Django
Need a hint?

Use os.getenv('SECRET_KEY') to read the variable from the environment.

4
Add a fallback default for SECRET_KEY
Modify the SECRET_KEY assignment to provide a fallback string 'fallback-secret-key' if the environment variable is missing. Use SECRET_KEY = os.getenv('SECRET_KEY', 'fallback-secret-key').
Django
Need a hint?

The second argument to os.getenv is the default value if the variable is not set.