Welcome back to CodeYourCraft! Today, we're going to dive into one of the essential topics for Django development - Environment Variables. We'll learn why they're important, how to use them, and even write some code to practice. π‘
Environment Variables are simple key-value pairs that store configuration data for an application. They provide a flexible way to manage settings that may vary between different environments, such as development, staging, and production.
Django supports using Environment Variables through the django.core.env module. Here's how to get started:
python-decouple package:pip install python-decouplesettings.py, import the necessary modules and add the following code to your settings:from decouple import config
# ...
# Load environment variables
# The .env file should be in the project's root directory
import os
basedir = os.path.abspath(os.path.dirname(__file__))
env_file = os.path.join(basedir, '.env')
if os.path.exists(env_file):
os.environ.update(dict(config(env_file))).env file in your project's root directory and add environment variables:DATABASE_URL=postgres://username:password@localhost:5432/mydb
API_KEY=1234567890
import os
API_KEY = config('API_KEY')config() function to load environment variables from the .env file.dotenv to manage them.Let's create a simple view that retrieves a secret API key from the Environment Variables:
from django.http import JsonResponse
def api_key_view(request):
api_key = config('API_KEY')
return JsonResponse({'api_key': api_key})What is the purpose of using Environment Variables in Django?