Django Tutorial: Environment Variables 🎯

beginner
14 min

Django Tutorial: Environment Variables 🎯

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. πŸ’‘

What are Environment Variables? πŸ“

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.

Why use Environment Variables? πŸ“

  1. Separation of Configurations: Environment Variables help keep sensitive data like database credentials and API keys out of the codebase, making it more secure.
  2. Easy Configuration Management: You can change settings quickly for different environments without modifying the code or deploying a new version.
  3. Portability: Environment Variables allow you to configure an application the same way across different environments, making it easier to deploy and maintain.

How to Use Environment Variables in Django πŸ’‘

Django supports using Environment Variables through the django.core.env module. Here's how to get started:

  1. Install the python-decouple package:
bash
pip install python-decouple
  1. In your Django project's settings.py, import the necessary modules and add the following code to your settings:
python
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)))
  1. Create a .env file in your project's root directory and add environment variables:
DATABASE_URL=postgres://username:password@localhost:5432/mydb API_KEY=1234567890
  1. Access the Environment Variables in your code:
python
import os API_KEY = config('API_KEY')

πŸ“ Note:

  • Use the config() function to load environment variables from the .env file.
  • When running locally, make sure to set the environment variables manually or use a tool like dotenv to manage them.

Practical Example πŸ’‘

Let's create a simple view that retrieves a secret API key from the Environment Variables:

python
from django.http import JsonResponse def api_key_view(request): api_key = config('API_KEY') return JsonResponse({'api_key': api_key})

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of using Environment Variables in Django?